text
stringlengths
184
4.48M
import { useEffect, useState } from "react"; import { Link, useParams } from "react-router-dom"; import { db } from "../../config/firebase"; import { doc, getDoc } from "firebase/firestore"; import { Button, Card, ProgressBar, Container, Col, Row } from "react-bootstrap"; import DonorForm from "../DonorForm/DonorForm"; import styles from "../Organisation/Organisation.module.css"; import PastItemDonations from "../DonorForm/PastItemDonations"; function ItemPage() { let params = useParams(); const [item, setItem] = useState<any>([]); useEffect(() => { const fetchData = async () => { const itemID = params.itemID || ""; const orgID = params.orgID || ""; const docRef = doc(db, `Organisations/${orgID}/Items`, itemID); const docSnap = await getDoc(docRef); setItem(docSnap.data()); }; fetchData().catch(console.error); }, [params.itemID, params.orgID]); const [org, setOrg] = useState<any>([]); useEffect(() => { const fetchData = async () => { const orgId = params.orgID || ""; const docRef = doc(db, "Organisations", orgId); const docSnap = await getDoc(docRef); setOrg(docSnap.data()); }; fetchData().catch(console.error); }, [params.orgID]); useEffect(() => { window.scrollTo(0, 0) }, []) return ( <div style={{ backgroundColor: "black", paddingTop: 10 }}> <Container fluid> <Row style={{ marginTop: "15px" }}> <Col className={styles.orgsContainer}> <Card className={styles.orgInfo}> <h6 style={{ textAlign: "left", margin: "7px", fontSize: "16px", color:"#FF7000" }}> <i>YOUR PARTNERSHIP MEANS THE WORLD TO US</i> </h6> <Card.Title style={{ fontSize:"35px" }}>{org.name}</Card.Title> <Card.Subtitle>would love your support for <br /> <em style={{ fontSize:"30px" }}>{item.name}</em> </Card.Subtitle> <Card.Img variant="top" src={item.img} alt={"Image of " + `${item.name}`} /> <Card.Body className="pt-0 px-0"> <br /> <Card.Text className="mb-0"> ${item.totalDonationsValue || 0} of $ {item.initialPrice} </Card.Text> <br /> <ProgressBar striped className="mb-3" now={ item.totalDonationsValue ? (item.totalDonationsValue / item.initialPrice) * 100 : 0 } label={`${Math.round( (item.totalDonationsValue / item.initialPrice) * 100 )}%`} /> <Card.Text>{item.description}</Card.Text> {org.website && <Card.Text> Check out the <a href={org.website}>{`${org.name}`} website</a></Card.Text>} </Card.Body> <Link to="/"> <Button className="goBackBtn" variant="warning">Go back</Button> </Link> </Card> </Col> <Col className={styles.formContainer}> <DonorForm org={params.orgID} item={params.itemID} itemName={item.name} itemOrgName={org.name} itemAmount={Math.round((item.initialPrice - (item.totalDonationsValue || 0) + Number.EPSILON) * 100) / 100} /> </Col> <Col className={styles.donorsContainer} style={{marginTop: "40px"}}> <div style={{ padding: "5vw", paddingTop: "0px"}}> <PastItemDonations /> </div> </Col> </Row> </Container> </div> ); } export default ItemPage;
const generateTree = (arr) => { if (!arr.length) { return null } const root = new TreeNode(arr[0]) const queue = [root] for (let i = 1; i < arr.length; i += 2) { const node = queue.shift() if (arr[i] !== null) { node.left = new TreeNode(arr[i]) queue.push(node.left) } if (arr[i + 1] !== null) { node.right = new TreeNode(arr[i + 1]) queue.push(node.right) } } return root } function TreeNode(val, left, right) { this.val = val === undefined ? 0 : val this.left = left === undefined ? null : left this.right = right === undefined ? null : right } /** * @param {TreeNode} root * @return {number} */ var diameterOfBinaryTree = function (root) { let ans = 0 const dfs = (node) => { if (!node) { return 0 } const leftDepth = dfs(node.left) const rightDepth = dfs(node.right) if (leftDepth + rightDepth > ans) { ans = leftDepth + rightDepth } return Math.max(leftDepth, rightDepth) + 1 } dfs(root) return ans } const tree = generateTree([1, 2, 3, 4, 5]) console.log(diameterOfBinaryTree(tree))
package com.app.server.service.aaaboundedcontext.authentication; import com.app.server.service.EntityTestCriteria; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.app.config.WebConfigExtended; import org.springframework.test.context.ContextConfiguration; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.springframework.test.context.TestExecutionListeners; import com.app.server.repository.aaaboundedcontext.authentication.PasswordAlgoRepository; import com.app.shared.aaaboundedcontext.authentication.PasswordAlgo; import org.springframework.beans.factory.annotation.Autowired; import com.athena.framework.server.helper.RuntimeLogInfoHelper; import com.athena.framework.server.helper.EntityValidatorHelper; import com.athena.framework.server.test.RandomValueGenerator; import java.util.HashMap; import java.util.List; import com.spartan.healthmeter.entity.scheduler.ArtMethodCallStack; import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.junit.Before; import org.junit.After; import com.athena.framework.shared.entity.web.entityInterface.CommonEntityInterface.RECORD_TYPE; import org.junit.Test; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; import com.athena.framework.server.exception.biz.SpartanIncorrectDataException; import com.athena.framework.server.exception.repository.SpartanPersistenceException; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfigExtended.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @TestExecutionListeners({ org.springframework.test.context.support.DependencyInjectionTestExecutionListener.class, org.springframework.test.context.support.DirtiesContextTestExecutionListener.class, org.springframework.test.context.transaction.TransactionalTestExecutionListener.class }) public class PasswordAlgoTestCase extends EntityTestCriteria { @Autowired private PasswordAlgoRepository<PasswordAlgo> passwordalgoRepository; @Autowired private RuntimeLogInfoHelper runtimeLogInfoHelper; @Autowired private EntityValidatorHelper<Object> entityValidator; private RandomValueGenerator valueGenerator = new RandomValueGenerator(); private static HashMap<String, Object> map = new HashMap<String, Object>(); private static List<EntityTestCriteria> entityContraint; @Autowired private ArtMethodCallStack methodCallStack; protected MockHttpSession session; protected MockHttpServletRequest request; protected MockHttpServletResponse response; protected void startSession() { session = new MockHttpSession(); } protected void endSession() { session.clearAttributes(); session.invalidate(); session = null; } protected void startRequest() { request = new MockHttpServletRequest(); request.setSession(session); org.springframework.web.context.request.RequestContextHolder.setRequestAttributes(new org.springframework.web.context.request.ServletRequestAttributes(request)); } protected void endRequest() { ((org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).requestCompleted(); org.springframework.web.context.request.RequestContextHolder.resetRequestAttributes(); request = null; } @Before public void before() { startSession(); startRequest(); setBeans(); } @After public void after() { endSession(); endRequest(); } private void setBeans() { runtimeLogInfoHelper.createRuntimeLogUserInfo(1, "AAAAA", request.getRemoteHost()); org.junit.Assert.assertNotNull(runtimeLogInfoHelper); methodCallStack.setRequestId(java.util.UUID.randomUUID().toString().toUpperCase()); entityContraint = addingListOfFieldForNegativeTesting(); } private PasswordAlgo createPasswordAlgo(Boolean isSave) throws SpartanPersistenceException, SpartanConstraintViolationException { PasswordAlgo passwordalgo = new PasswordAlgo(); passwordalgo.setAlgoName("ooLYcyWNbBnxKPmnK4Wry1BqADrDHQ57oi2JfEUJIPKLRvuCCv"); passwordalgo.setAlgoHelp("gYtKq8f5g0dFOr8qzVyearVP0oAbUQP6A8WN6SLxifPBfRI47i"); passwordalgo.setAlgoIcon("dYWTI6x60ZCxxKHv24xJlvEiN7U44LUcBrghln0EgxcNeciDxZ"); passwordalgo.setAlgoDescription("JyBKZX3Dw7D0bL6Gay6UOvAMdbOOpOCC6KDnSbiz0oqUY2jwOe"); passwordalgo.setAlgorithm(6); passwordalgo.setEntityValidator(entityValidator); return passwordalgo; } @Test public void test1Save() { try { PasswordAlgo passwordalgo = createPasswordAlgo(true); passwordalgo.setEntityAudit(1, "xyz", RECORD_TYPE.ADD); passwordalgo.isValid(); passwordalgoRepository.save(passwordalgo); map.put("PasswordAlgoPrimaryKey", passwordalgo._getPrimarykey()); } catch (com.athena.framework.server.exception.biz.SpartanConstraintViolationException e) { org.junit.Assert.fail(e.getMessage()); } catch (java.lang.Exception e) { org.junit.Assert.fail(e.getMessage()); } } @Test public void test2Update() { try { org.junit.Assert.assertNotNull(map.get("PasswordAlgoPrimaryKey")); PasswordAlgo passwordalgo = passwordalgoRepository.findById((java.lang.String) map.get("PasswordAlgoPrimaryKey")); passwordalgo.setAlgoName("8usTWPhVlB4LnXMpVIycjFUGzfArVN4f6UaTwFf3bQmU0ps8d2"); passwordalgo.setVersionId(1); passwordalgo.setAlgoHelp("TeAi5ZUeATU3498oI9jQ90Jrpj6Ih9FU6BDGzZwW17IwW5mfHk"); passwordalgo.setAlgoIcon("24cOm5rGslRsGATHTPjhO76mJ2rpHEsEtn00eVPDUE5DDVpjo2"); passwordalgo.setAlgoDescription("lwiuIBQczc2XK4uIBAFVNDG3ruuiI14BkctCE8qX5pYpYVA0jN"); passwordalgo.setAlgorithm(1); passwordalgo.setEntityAudit(1, "xyz", RECORD_TYPE.UPDATE); passwordalgoRepository.update(passwordalgo); } catch (com.athena.framework.server.exception.repository.SpartanPersistenceException e) { org.junit.Assert.fail(e.getMessage()); } catch (java.lang.Exception e) { org.junit.Assert.fail(e.getMessage()); } } @Test public void test3FindById() { try { org.junit.Assert.assertNotNull(map.get("PasswordAlgoPrimaryKey")); passwordalgoRepository.findById((java.lang.String) map.get("PasswordAlgoPrimaryKey")); } catch (com.athena.framework.server.exception.repository.SpartanPersistenceException e) { org.junit.Assert.fail(e.getMessage()); } catch (Exception e) { org.junit.Assert.fail(e.getMessage()); } } @Test public void test6Delete() { try { org.junit.Assert.assertNotNull(map.get("PasswordAlgoPrimaryKey")); passwordalgoRepository.delete((java.lang.String) map.get("PasswordAlgoPrimaryKey")); } catch (com.athena.framework.server.exception.repository.SpartanPersistenceException e) { org.junit.Assert.fail(e.getMessage()); } catch (Exception e) { org.junit.Assert.fail(e.getMessage()); } } private void validatePasswordAlgo(EntityTestCriteria contraints, PasswordAlgo passwordalgo) throws SpartanIncorrectDataException, SpartanConstraintViolationException, SpartanPersistenceException { if (contraints.getRuleType() == MIN_MAX) { passwordalgo.isValid(); } else if (contraints.getRuleType() == NOT_NULL) { passwordalgo.isValid(); } else if (contraints.getRuleType() == REGEX) { passwordalgo.isValid(); } else if (contraints.getRuleType() == UNIQUE) { passwordalgoRepository.save(passwordalgo); } } private List<EntityTestCriteria> addingListOfFieldForNegativeTesting() { List<EntityTestCriteria> entityContraints = new java.util.ArrayList<EntityTestCriteria>(); entityContraints.add(new EntityTestCriteria(NOT_NULL, 1, "algorithm", null)); entityContraints.add(new EntityTestCriteria(MIN_MAX, 2, "algorithm", 19)); entityContraints.add(new EntityTestCriteria(NOT_NULL, 3, "algoName", null)); entityContraints.add(new EntityTestCriteria(MIN_MAX, 4, "algoName", "48ithUge3TbPISy06tf0dLbNjhGr3mcyi53rNJURBb95zVfJJqU7zG4rrlaAtWQ7OkvCGcAAZvB7rhpI74BNdGErX2Rxh65Lw0oBtjCAgaZaCLOis0b6xfpsMNKY4uNhY6eGdPQ7CyjUPmwUA0Onj4dNwxw8ae6cdlCkCn4ElyiskEXmRiZ8ElJlHLpSdHcri35MG9u7ed9d6TBppgszZMcFaFGjwaPXPxYimxwWSXhqTvTYk5AkO8uVYz8SIBtLM")); entityContraints.add(new EntityTestCriteria(MIN_MAX, 5, "algoDescription", "wmcAyyi9JjN3BjyFJjR9NfauqkrxG4VIM1EehwALsT53gQWmqWFFRsNWh4NLXpGsPJ8dYkcTs5eNVAxUBR7AzaDo3bOLuih9I97MmI3GqgdscmHYpNBJpNPhrZG5kOUB5OBHut2Ub1FRV4NkDDierigq57Z5PzueELo4pZ6eF1QiehOh04uTscMDrcZwTYPh5EmAf1I1X8fVni2oA3sb21qOWxnXVd0NQKKv6jBdoZr817Z7TJipfGbzHzJY9EjhI")); entityContraints.add(new EntityTestCriteria(MIN_MAX, 6, "algoIcon", "3SKS4biDFIEP7eqchr3WhUUPuXn3LM3HZsbQ0tzYbSUqfxoyk2592WdXwvQ2NoX5z")); entityContraints.add(new EntityTestCriteria(MIN_MAX, 7, "algoHelp", "CeQsCLQHvwADjWqFEYGu9FFmXIr1rDRVQEaX1c5b98LBr6P4mggZuHiMyKXexcK3raNTjNKYJpHR399YCWTyOLdWSYGXn5UeYYrYfBQKHfdLa1tF3erjslUtHWdkIFUXbegupcppBK2KyOOMf62M9xmjPHYNIZhxX9djOqzZRdVPV2g5GZltr9YjMocibpBZWfsztCA6M56cJvj3yC8QLZOE9p5mmjBfz8fgodqX6UvOYjol9XzZpG39u89kPPotw")); return entityContraints; } @Test public void test5NegativeTesting() throws NoSuchMethodException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, Exception, SpartanPersistenceException { int failureCount = 0; for (EntityTestCriteria contraints : this.entityContraint) { try { PasswordAlgo passwordalgo = createPasswordAlgo(false); java.lang.reflect.Field field = null; if (!contraints.getFieldName().equalsIgnoreCase("CombineUniqueKey")) { field = passwordalgo.getClass().getDeclaredField(contraints.getFieldName()); } switch(((contraints.getTestId()))) { case 0: break; case 1: field.setAccessible(true); field.set(passwordalgo, null); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; case 2: passwordalgo.setAlgorithm(Integer.parseInt(contraints.getNegativeValue().toString())); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; case 3: field.setAccessible(true); field.set(passwordalgo, null); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; case 4: passwordalgo.setAlgoName(contraints.getNegativeValue().toString()); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; case 5: passwordalgo.setAlgoDescription(contraints.getNegativeValue().toString()); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; case 6: passwordalgo.setAlgoIcon(contraints.getNegativeValue().toString()); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; case 7: passwordalgo.setAlgoHelp(contraints.getNegativeValue().toString()); validatePasswordAlgo(contraints, passwordalgo); failureCount++; break; } } catch (SpartanIncorrectDataException e) { e.printStackTrace(); } catch (SpartanConstraintViolationException e) { e.printStackTrace(); } catch (SpartanPersistenceException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if (failureCount > 0) { org.junit.Assert.fail(); } } }
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Facades\Storage; use Laravel\Sanctum\HasApiTokens; use Laravel\Cashier\Billable; class User extends Authenticatable implements MustVerifyEmail { use HasApiTokens, HasFactory, Notifiable, SoftDeletes, Billable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'UsersName', 'email', 'password', 'phone', 'image', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; // Cart public function carts() { return $this->hasMany(Cart::class)->with('product'); } // revenues public function revenues() { return $this->hasMany(Revenue::class); } public function checkouts() { return $this->hasMany(Checkout::class)->with('products'); } // fULL name public function getFullNameAttribute() { return $this->UsersName; } // Image public function imageUrl(): Attribute { return Attribute::make( get: fn () => $this->image == null ? asset('ase/assets/img/avatars/blank-profile.png') : Storage::url($this->image) ); } }
package com.example.pill import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import com.example.pill.databinding.ActivityHomeBinding import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.floatingactionbutton.FloatingActionButton class Home : AppCompatActivity() { private lateinit var bottomNavigationView: BottomNavigationView private lateinit var binding: ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) //get data from login val intent = intent val userId = intent.getIntExtra("id", 0) val userEmail = intent.getStringExtra("email") val userFName = intent.getStringExtra("fname") //assign the data to the bundle for passing of data to home and profile fragments //solution1 // val bundle = Bundle() // bundle.putInt("userId", userId) // bundle.putString("userEmail", userEmail) // bundle.putString("userFullName", userFName) //nasa home.xml to eto yung mismong bottom nav natin bottomNavigationView = findViewById(R.id.bottom_navigation) bottomNavigationView.itemActiveIndicatorColor = getColorStateList(R.color.white) //menuItem is associated with itemId //switch statement lang din yung when bottomNavigationView.setOnItemSelectedListener { menuItem -> when(menuItem.itemId){ R.id.bottom_home -> { val hfragment = HomeFragment() //pass data to home fragment // hfragment.arguments = bundle replaceFragment(hfragment) true } R.id.bottom_profile -> { val pfragment = ProfileFragment() //pass data to profile fragment // pfragment.arguments = bundle replaceFragment(pfragment) true } else -> false } } //default fragment replaceFragment(HomeFragment()) //fab onclicklistener to addDosage Activity val btnaddDosage = findViewById<FloatingActionButton>(R.id.fabAddDosage) btnaddDosage.setOnClickListener { val addDoseIntent = Intent(this, AddDose::class.java) startActivity(addDoseIntent) } //pass data to profilefragment // val fragment = ProfileFragment() // val bundle = Bundle() // bundle.putString("fullName", userFName) // fragment.arguments = bundle // supportFragmentManager.beginTransaction().add(R.id.frame_container, fragment).commit() } //dito mangyayare yung magpapalit ng fragement based don sa clinick na icon, gumamit ng replace method para palitan yung fragment //yung frame_container yan yung current fragment id natin sa home.xml //fragment yun yung magiging new fragment based don sa ipapasang parameter private fun replaceFragment(fragment: Fragment){ supportFragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit() } }
function printAndSum(start, end) { let sum = 0; let output = ''; for (let index = start; index <= end; index++) { sum += index; //при всяка итерация към сумата се добавя (сумира) индекса, в който се намираме output += `${index} `; //използва се конкатенация за да се отпечати всичко на един ред последователно (постепенна конкатенация, с всяко завъртане на цикъла) //към аутпут променлвита горе, се добавям индекса и един СПЕЙС (за да не се долепят отделните индекси) } console.log(output); console.log(`Sum: ${sum}`); } printAndSum(50, 60)
import json import shlex import unittest.mock as mock from aws_interactions.aws_environment import AwsEnvironment from aws_interactions.ssm_operations import ParamDoesNotExist import cdk_interactions.cdk_context as context from commands.cluster_destroy import (cmd_cluster_destroy, _destroy_viewer_cert, _delete_arkime_config_from_datastore, _get_stacks_to_destroy, _get_cdk_context) import core.constants as constants from core.capacity_planning import (CaptureNodesPlan, ViewerNodesPlan, EcsSysResourcePlan, OSDomainPlan, DataNodesPlan, MasterNodesPlan, ClusterPlan, VpcPlan, S3Plan, DEFAULT_S3_STORAGE_CLASS, DEFAULT_VPC_CIDR, DEFAULT_CAPTURE_PUBLIC_MASK, DEFAULT_NUM_AZS, DEFAULT_S3_STORAGE_DAYS) from core.user_config import UserConfig TEST_CLUSTER = "my-cluster" @mock.patch("commands.cluster_destroy.get_ssm_param_json_value") @mock.patch("commands.cluster_destroy._get_cdk_context") @mock.patch("commands.cluster_destroy._get_stacks_to_destroy") @mock.patch("commands.cluster_destroy.AwsClientProvider") @mock.patch("commands.cluster_destroy._delete_arkime_config_from_datastore") @mock.patch("commands.cluster_destroy._destroy_viewer_cert") @mock.patch("commands.cluster_destroy.get_ssm_names_by_path") @mock.patch("commands.cluster_destroy.destroy_os_domain_and_wait") @mock.patch("commands.cluster_destroy.destroy_bucket") @mock.patch("commands.cluster_destroy.CdkClient") def test_WHEN_cmd_cluster_destroy_called_AND_dont_destroy_everything_THEN_expected_cmds(mock_cdk_client_cls, mock_destroy_bucket, mock_destroy_domain, mock_ssm_get, mock_destroy_cert, mock_delete_arkime, mock_aws_provider_cls, mock_get_stacks, mock_get_context, mock_get_json): # Set up our mock mock_ssm_get.return_value = [] mock_client = mock.Mock() mock_cdk_client_cls.return_value = mock_client aws_env = AwsEnvironment("XXXXXXXXXXXX", "region", "profile") mock_aws_provider = mock.Mock() mock_aws_provider.get_aws_env.return_value = aws_env mock_aws_provider_cls.return_value = mock_aws_provider mock_get_stacks.return_value = ["stack1", "stack2"] mock_get_context.return_value = {"key": "value"} test_plan = ClusterPlan( CaptureNodesPlan("m5.xlarge", 1, 2, 1), VpcPlan(DEFAULT_VPC_CIDR, DEFAULT_NUM_AZS, DEFAULT_CAPTURE_PUBLIC_MASK), EcsSysResourcePlan(3584, 15360), OSDomainPlan(DataNodesPlan(2, "t3.small.search", 100), MasterNodesPlan(3, "m6g.large.search")), S3Plan(DEFAULT_S3_STORAGE_CLASS, DEFAULT_S3_STORAGE_DAYS), ViewerNodesPlan(4, 2), None ) mock_get_json.return_value = test_plan.to_dict() # Run our test cmd_cluster_destroy("profile", "region", TEST_CLUSTER, False) # Check our results mock_destroy_bucket.assert_not_called() mock_destroy_domain.assert_not_called() expected_stacks_calls = [mock.call(TEST_CLUSTER, False, False)] assert expected_stacks_calls == mock_get_stacks.call_args_list expected_cdk_calls = [mock.call(TEST_CLUSTER, False)] assert expected_cdk_calls == mock_get_context.call_args_list expected_calls = [ mock.call( ["stack1", "stack2"], context={"key": "value"} ) ] assert expected_calls == mock_client.destroy.call_args_list expected_cdk_client_create_calls = [ mock.call(aws_env) ] assert expected_cdk_client_create_calls == mock_cdk_client_cls.call_args_list expected_destroy_calls = [ mock.call(TEST_CLUSTER, mock.ANY) ] assert expected_destroy_calls == mock_destroy_cert.call_args_list expected_delete_arkime_calls = [ mock.call(TEST_CLUSTER, mock.ANY) ] assert expected_delete_arkime_calls == mock_delete_arkime.call_args_list @mock.patch("commands.cluster_destroy._get_cdk_context") @mock.patch("commands.cluster_destroy._get_stacks_to_destroy") @mock.patch("commands.cluster_destroy.AwsClientProvider") @mock.patch("commands.cluster_destroy._delete_arkime_config_from_datastore") @mock.patch("commands.cluster_destroy._destroy_viewer_cert") @mock.patch("commands.cluster_destroy.get_ssm_names_by_path") @mock.patch("commands.cluster_destroy.destroy_os_domain_and_wait") @mock.patch("commands.cluster_destroy.destroy_bucket") @mock.patch("commands.cluster_destroy.get_ssm_param_json_value") @mock.patch("commands.cluster_destroy.get_ssm_param_value") @mock.patch("commands.cluster_destroy.CdkClient") def test_WHEN_cmd_cluster_destroy_called_AND_destroy_everything_THEN_expected_cmds(mock_cdk_client_cls, mock_get_ssm, mock_get_ssm_json, mock_destroy_bucket,mock_destroy_domain, mock_ssm_names, mock_destroy_cert, mock_delete_arkime, mock_aws_provider_cls, mock_get_stacks, mock_get_context): # Set up our mock mock_ssm_names.return_value = [] mock_client = mock.Mock() mock_cdk_client_cls.return_value = mock_client aws_env = AwsEnvironment("XXXXXXXXXXXX", "region", "profile") mock_aws_provider = mock.Mock() mock_aws_provider.get_aws_env.return_value = aws_env mock_aws_provider_cls.return_value = mock_aws_provider test_plan = ClusterPlan( CaptureNodesPlan("m5.xlarge", 1, 2, 1), VpcPlan(DEFAULT_VPC_CIDR, DEFAULT_NUM_AZS, DEFAULT_CAPTURE_PUBLIC_MASK), EcsSysResourcePlan(3584, 15360), OSDomainPlan(DataNodesPlan(2, "t3.small.search", 100), MasterNodesPlan(3, "m6g.large.search")), S3Plan(DEFAULT_S3_STORAGE_CLASS, DEFAULT_S3_STORAGE_DAYS), ViewerNodesPlan(4, 2), VpcPlan(DEFAULT_VPC_CIDR, DEFAULT_NUM_AZS, DEFAULT_CAPTURE_PUBLIC_MASK), ) mock_get_ssm_json.side_effect = [test_plan.to_dict(), "arkime-domain"] mock_get_ssm.return_value = "capture-bucket" mock_get_stacks.return_value = ["stack1", "stack2"] mock_get_context.return_value = {"key": "value"} # Run our test cmd_cluster_destroy("profile", "region", TEST_CLUSTER, True) # Check our results expected_destroy_domain_calls = [ mock.call( domain_name="arkime-domain", aws_client_provider=mock.ANY ) ] assert expected_destroy_domain_calls == mock_destroy_domain.call_args_list expected_destroy_bucket_calls = [ mock.call( bucket_name="capture-bucket", aws_provider=mock.ANY ) ] assert expected_destroy_bucket_calls == mock_destroy_bucket.call_args_list expected_stacks_calls = [mock.call(TEST_CLUSTER, True, True)] assert expected_stacks_calls == mock_get_stacks.call_args_list expected_cdk_calls = [mock.call(TEST_CLUSTER, True)] assert expected_cdk_calls == mock_get_context.call_args_list expected_cdk_calls = [ mock.call( ["stack1", "stack2"], context={"key": "value"} ) ] assert expected_cdk_calls == mock_client.destroy.call_args_list expected_cdk_client_create_calls = [ mock.call(aws_env) ] assert expected_cdk_client_create_calls == mock_cdk_client_cls.call_args_list expected_destroy_calls = [ mock.call(TEST_CLUSTER, mock.ANY) ] assert expected_destroy_calls == mock_destroy_cert.call_args_list expected_delete_arkime_calls = [ mock.call(TEST_CLUSTER, mock.ANY) ] assert expected_delete_arkime_calls == mock_delete_arkime.call_args_list @mock.patch("commands.cluster_destroy.AwsClientProvider", mock.Mock()) @mock.patch("commands.cluster_destroy.get_ssm_param_json_value") @mock.patch("commands.cluster_destroy.get_ssm_names_by_path") @mock.patch("commands.cluster_destroy.destroy_os_domain_and_wait") @mock.patch("commands.cluster_destroy.destroy_bucket") @mock.patch("commands.cluster_destroy.CdkClient") def test_WHEN_cmd_cluster_destroy_called_AND_existing_captures_THEN_abort(mock_cdk_client_cls, mock_destroy_bucket, mock_destroy_domain, mock_ssm_names, mock_get_ssm_json): # Set up our mock mock_ssm_names.return_value = ["vpc-1", "vpc-2"] mock_client = mock.Mock() mock_cdk_client_cls.return_value = mock_client test_plan = ClusterPlan( CaptureNodesPlan("m5.xlarge", 1, 2, 1), VpcPlan(DEFAULT_VPC_CIDR, DEFAULT_NUM_AZS, DEFAULT_CAPTURE_PUBLIC_MASK), EcsSysResourcePlan(3584, 15360), OSDomainPlan(DataNodesPlan(2, "t3.small.search", 100), MasterNodesPlan(3, "m6g.large.search")), S3Plan(DEFAULT_S3_STORAGE_CLASS, DEFAULT_S3_STORAGE_DAYS), ViewerNodesPlan(4, 2), None ) mock_get_ssm_json.side_effect = [test_plan.to_dict(), "arkime-domain"] # Run our test cmd_cluster_destroy("profile", "region", TEST_CLUSTER, False) # Check our results mock_destroy_bucket.assert_not_called() mock_destroy_domain.assert_not_called() mock_client.destroy.assert_not_called() @mock.patch("commands.cluster_destroy.AwsClientProvider", mock.Mock()) @mock.patch("commands.cluster_destroy.get_ssm_param_json_value") @mock.patch("commands.cluster_destroy.get_ssm_names_by_path") @mock.patch("commands.cluster_destroy.destroy_os_domain_and_wait") @mock.patch("commands.cluster_destroy.destroy_bucket") @mock.patch("commands.cluster_destroy.CdkClient") def test_WHEN_cmd_cluster_destroy_called_AND_doesnt_exist_THEN_abort(mock_cdk_client_cls, mock_destroy_bucket, mock_destroy_domain, mock_ssm_names, mock_get_ssm_json): # Set up our mock mock_ssm_names.return_value = ["vpc-1", "vpc-2"] mock_client = mock.Mock() mock_cdk_client_cls.return_value = mock_client mock_get_ssm_json.side_effect = ParamDoesNotExist("") # Run our test cmd_cluster_destroy("profile", "region", TEST_CLUSTER, False) # Check our results mock_destroy_bucket.assert_not_called() mock_destroy_domain.assert_not_called() mock_client.destroy.assert_not_called() @mock.patch("commands.cluster_destroy.delete_ssm_param") @mock.patch("commands.cluster_destroy.destroy_cert") @mock.patch("commands.cluster_destroy.get_ssm_param_value") def test_WHEN_destroy_viewer_cert_called_THEN_as_expected(mock_ssm_get, mock_destroy_cert, mock_ssm_delete): # Set up our mock mock_ssm_get.return_value = "arn" mock_provider = mock.Mock() # Run our test _destroy_viewer_cert(TEST_CLUSTER, mock_provider) # Check our results expected_get_ssm_calls = [ mock.call( constants.get_viewer_cert_ssm_param_name(TEST_CLUSTER), mock_provider ) ] assert expected_get_ssm_calls == mock_ssm_get.call_args_list expected_destroy_cert_calls = [ mock.call("arn", mock_provider) ] assert expected_destroy_cert_calls == mock_destroy_cert.call_args_list expected_delete_ssm_calls = [ mock.call( constants.get_viewer_cert_ssm_param_name(TEST_CLUSTER), mock_provider ) ] assert expected_delete_ssm_calls == mock_ssm_delete.call_args_list @mock.patch("commands.cluster_destroy.delete_ssm_param") @mock.patch("commands.cluster_destroy.destroy_cert") @mock.patch("commands.cluster_destroy.get_ssm_param_value") def test_WHEN_destroy_viewer_cert_called_AND_doesnt_exist_THEN_skip(mock_ssm_get, mock_destroy_cert, mock_ssm_delete): # Set up our mock mock_ssm_get.side_effect = ParamDoesNotExist("") mock_provider = mock.Mock() # Run our test _destroy_viewer_cert(TEST_CLUSTER, mock_provider) # Check our results expected_get_ssm_calls = [ mock.call( constants.get_viewer_cert_ssm_param_name(TEST_CLUSTER), mock_provider ) ] assert expected_get_ssm_calls == mock_ssm_get.call_args_list expected_destroy_cert_calls = [] assert expected_destroy_cert_calls == mock_destroy_cert.call_args_list expected_delete_ssm_calls = [] assert expected_delete_ssm_calls == mock_ssm_delete.call_args_list @mock.patch("commands.cluster_destroy.destroy_bucket") @mock.patch("commands.cluster_destroy.delete_ssm_param") def test_WHEN_delete_arkime_config_from_datastore_called_THEN_as_expected(mock_ssm_delete, mock_destroy_bucket): # Set up our mock test_env = AwsEnvironment("XXXXXXXXXXX", "my-region-1", "profile") mock_provider = mock.Mock() mock_provider.get_aws_env.return_value = test_env # Run our test _delete_arkime_config_from_datastore(TEST_CLUSTER, mock_provider) # Check our results expected_delete_ssm_calls = [ mock.call( constants.get_capture_config_details_ssm_param_name(TEST_CLUSTER), mock_provider ), mock.call( constants.get_viewer_config_details_ssm_param_name(TEST_CLUSTER), mock_provider ), ] assert expected_delete_ssm_calls == mock_ssm_delete.call_args_list expected_destroy_bucket_calls = [ mock.call( bucket_name=constants.get_config_bucket_name( test_env.aws_account, test_env.aws_region, TEST_CLUSTER ), aws_provider=mock_provider ) ] assert expected_destroy_bucket_calls == mock_destroy_bucket.call_args_list def test_WHEN_get_stacks_to_destroy_called_THEN_as_expected(): cluster_name = "MyCluster" # TEST: Don't destroy everything, no Viewer VPC actual_value = _get_stacks_to_destroy(cluster_name, False, False) expected_value = [ constants.get_capture_nodes_stack_name(cluster_name), constants.get_viewer_nodes_stack_name(cluster_name), ] assert expected_value == actual_value # TEST: Don't destroy everything, has Viewer VPC actual_value = _get_stacks_to_destroy(cluster_name, False, True) expected_value = [ constants.get_capture_nodes_stack_name(cluster_name), constants.get_viewer_nodes_stack_name(cluster_name), constants.get_capture_tgw_stack_name(cluster_name), constants.get_viewer_vpc_stack_name(cluster_name), ] assert expected_value == actual_value # TEST: Destroy everything, no Viewer VPC actual_value = _get_stacks_to_destroy(cluster_name, True, False) expected_value = [ constants.get_capture_bucket_stack_name(cluster_name), constants.get_capture_nodes_stack_name(cluster_name), constants.get_capture_vpc_stack_name(cluster_name), constants.get_opensearch_domain_stack_name(cluster_name), constants.get_viewer_nodes_stack_name(cluster_name) ] assert expected_value == actual_value # TEST: Destroy everything, has Viewer VPC actual_value = _get_stacks_to_destroy(cluster_name, True, True) expected_value = [ constants.get_capture_bucket_stack_name(cluster_name), constants.get_capture_nodes_stack_name(cluster_name), constants.get_capture_vpc_stack_name(cluster_name), constants.get_opensearch_domain_stack_name(cluster_name), constants.get_viewer_nodes_stack_name(cluster_name), constants.get_capture_tgw_stack_name(cluster_name), constants.get_viewer_vpc_stack_name(cluster_name), ] assert expected_value == actual_value def test_WHEN_get_cdk_context_called_AND_viewer_vpc_THEN_as_expected(): cluster_name = "MyCluster" default_plan = ClusterPlan( CaptureNodesPlan("m5.xlarge", 1, 2, 1), VpcPlan(DEFAULT_VPC_CIDR, 2, DEFAULT_CAPTURE_PUBLIC_MASK), EcsSysResourcePlan(1, 1), OSDomainPlan(DataNodesPlan(2, "t3.small.search", 100), MasterNodesPlan(3, "m6g.large.search")), S3Plan(DEFAULT_S3_STORAGE_CLASS, 1), ViewerNodesPlan(4, 2), VpcPlan(DEFAULT_VPC_CIDR, 2, DEFAULT_CAPTURE_PUBLIC_MASK), ) stack_names = context.ClusterStackNames( captureBucket=constants.get_capture_bucket_stack_name(cluster_name), captureNodes=constants.get_capture_nodes_stack_name(cluster_name), captureTgw=constants.get_capture_tgw_stack_name(cluster_name), captureVpc=constants.get_capture_vpc_stack_name(cluster_name), osDomain=constants.get_opensearch_domain_stack_name(cluster_name), viewerNodes=constants.get_viewer_nodes_stack_name(cluster_name), viewerVpc=constants.get_viewer_vpc_stack_name(cluster_name), ) actual_value = _get_cdk_context(cluster_name, True) expected_value = { constants.CDK_CONTEXT_CMD_VAR: constants.CMD_cluster_destroy, constants.CDK_CONTEXT_PARAMS_VAR: shlex.quote(json.dumps({ "nameCluster": cluster_name, "nameCaptureBucketSsmParam": constants.get_capture_bucket_ssm_param_name(cluster_name), "nameCaptureConfigSsmParam": constants.get_capture_config_details_ssm_param_name(cluster_name), "nameCaptureDetailsSsmParam": constants.get_capture_details_ssm_param_name(cluster_name), "nameClusterConfigBucket": "", "nameClusterSsmParam": constants.get_cluster_ssm_param_name(cluster_name), "nameOSDomainSsmParam": constants.get_opensearch_domain_ssm_param_name(cluster_name), "nameViewerCertArn": "N/A", "nameViewerConfigSsmParam": constants.get_viewer_config_details_ssm_param_name(cluster_name), "nameViewerDetailsSsmParam": constants.get_viewer_details_ssm_param_name(cluster_name), "planCluster": json.dumps(default_plan.to_dict()), "stackNames": json.dumps(stack_names.to_dict()), "userConfig": json.dumps(UserConfig(1, 1, 1, 1, 1).to_dict()), })) } assert expected_value == actual_value def test_WHEN_get_cdk_context_called_AND_no_viewer_vpc_THEN_as_expected(): cluster_name = "MyCluster" default_plan = ClusterPlan( CaptureNodesPlan("m5.xlarge", 1, 2, 1), VpcPlan(DEFAULT_VPC_CIDR, 2, DEFAULT_CAPTURE_PUBLIC_MASK), EcsSysResourcePlan(1, 1), OSDomainPlan(DataNodesPlan(2, "t3.small.search", 100), MasterNodesPlan(3, "m6g.large.search")), S3Plan(DEFAULT_S3_STORAGE_CLASS, 1), ViewerNodesPlan(4, 2), None, ) stack_names = context.ClusterStackNames( captureBucket=constants.get_capture_bucket_stack_name(cluster_name), captureNodes=constants.get_capture_nodes_stack_name(cluster_name), captureTgw=constants.get_capture_tgw_stack_name(cluster_name), captureVpc=constants.get_capture_vpc_stack_name(cluster_name), osDomain=constants.get_opensearch_domain_stack_name(cluster_name), viewerNodes=constants.get_viewer_nodes_stack_name(cluster_name), viewerVpc=constants.get_viewer_vpc_stack_name(cluster_name), ) actual_value = _get_cdk_context(cluster_name, False) expected_value = { constants.CDK_CONTEXT_CMD_VAR: constants.CMD_cluster_destroy, constants.CDK_CONTEXT_PARAMS_VAR: shlex.quote(json.dumps({ "nameCluster": cluster_name, "nameCaptureBucketSsmParam": constants.get_capture_bucket_ssm_param_name(cluster_name), "nameCaptureConfigSsmParam": constants.get_capture_config_details_ssm_param_name(cluster_name), "nameCaptureDetailsSsmParam": constants.get_capture_details_ssm_param_name(cluster_name), "nameClusterConfigBucket": "", "nameClusterSsmParam": constants.get_cluster_ssm_param_name(cluster_name), "nameOSDomainSsmParam": constants.get_opensearch_domain_ssm_param_name(cluster_name), "nameViewerCertArn": "N/A", "nameViewerConfigSsmParam": constants.get_viewer_config_details_ssm_param_name(cluster_name), "nameViewerDetailsSsmParam": constants.get_viewer_details_ssm_param_name(cluster_name), "planCluster": json.dumps(default_plan.to_dict()), "stackNames": json.dumps(stack_names.to_dict()), "userConfig": json.dumps(UserConfig(1, 1, 1, 1, 1).to_dict()), })) } assert expected_value == actual_value
import { BadRequestException, Injectable, NotFoundException, UnprocessableEntityException, } from '@nestjs/common'; import { InjectConnection, InjectRepository } from '@nestjs/typeorm'; import { Connection, EntityManager, In, Repository } from 'typeorm'; import _ from 'lodash'; import { CreateCategoryDto } from './dtos/create-category.dto'; import { UpdateCategoryDto } from './dtos/update-category-dto'; import { Category } from './entities/category.entity'; import { BatchUpdateCategoryDto } from './dtos/batch-update-category.dto'; @Injectable() export class CategoryService { @InjectConnection() private connection: Connection; @InjectRepository(Category) private categoryRepository: Repository<Category>; find(orgId: number): Promise<Category[]> { return this.categoryRepository.find({ orgId }); } findByIds(orgId: number, ids: number[]): Promise<Category[]> { return this.categoryRepository.find({ orgId, id: In(ids) }); } findOne(orgId: number, id: number): Promise<Category | undefined> { return this.categoryRepository.findOne({ orgId, id }); } async findOneOrFail(orgId: number, id: number): Promise<Category> { const category = await this.findOne(orgId, id); if (!category) { throw new NotFoundException(`category ${id} does not exist`); } return category; } async create(orgId: number, data: CreateCategoryDto): Promise<number> { const category = new Category(); category.orgId = orgId; Object.assign(category, data); await this.connection.transaction(async (manager) => { if (category.parentId) { const parent = await manager.findOne(Category, { where: { orgId, id: category.parentId, }, lock: { mode: 'pessimistic_read' }, }); if (!parent) { throw new NotFoundException('parent category does not exist'); } if (!parent.active) { throw new UnprocessableEntityException('parent category is inactive'); } } await manager.insert(Category, category); }); return category.id; } async update(orgId: number, id: number, data: UpdateCategoryDto) { await this.connection.transaction((manager) => this.updateByEntityManager(manager, orgId, id, data), ); } async batchUpdate( orgId: number, datas: BatchUpdateCategoryDto['categories'], ) { if (datas.length === 0) { return; } await this.connection.transaction(async (manager) => { for (const { id, ...data } of datas) { try { await this.updateByEntityManager(manager, orgId, id, data); } catch (error) { throw new BadRequestException( `failed to update category ${id}: ${error.message}`, ); } } }); } private async updateByEntityManager( manager: EntityManager, orgId: number, id: number, data: UpdateCategoryDto, ) { if (_.isEmpty(data)) { return; } if (data.parentId === id) { throw new BadRequestException('cannot set parentId to self'); } const findOne = (id: number) => manager.findOne(Category, { where: { orgId, id }, lock: { mode: 'pessimistic_read' }, }); const category = await findOne(id); if (!category) { throw new NotFoundException(`category ${id} does not exist`); } if (data.parentId !== null) { const parentId = data.parentId ?? category.parentId; if (parentId) { const parent = await findOne(parentId); if (!parent) { throw new UnprocessableEntityException( 'parent category does not exist', ); } if (!parent.active && (data.active ?? category.active)) { throw new BadRequestException( 'cannot make active category under an inactive parent', ); } } } if (data.active === false && data.active !== category.active) { const activeChild = await manager.findOne(Category, { where: { orgId, parentId: id, active: true, }, lock: { mode: 'pessimistic_read' }, }); if (activeChild) { throw new BadRequestException('some subcategories still active'); } } await manager.update(Category, { orgId, id }, data); } }
const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const morgan = require("morgan"); const mongoose = require("mongoose"); const routes = require("./src/routes"); mongoose.connect( "mongodb://avazalimov:" + process.env.MONGO_ATLAS_PASSWORD + "@app-shard-00-00-okl1f.mongodb.net:27017,app-shard-00-01-okl1f.mongodb.net:27017,app-shard-00-02-okl1f.mongodb.net:27017/test?ssl=true&replicaSet=app-shard-0&authSource=admin" ); mongoose.Promise = global.Promise; const app = express(); app.use(express.static(__dirname + "/../client/dist/")); app.use("/admin", express.static(__dirname + "/../client/admin/")); app.use("/uploads", express.static("uploads")); app.use(morgan("combined")); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use(cors()); routes(app); app.use((res, req, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization" ); if (req.method === "OPTIONS") { res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET"); return res.status(200).json({}); } next(); }); //Error 404 app.use((req, res, next) => { let err = new Error("Not Found"); err.status = 404; next(err); }); //Error 500 if (app.get("env") === "development") { app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ message: err.message, error: err }); }); } module.exports = app;
import UIKit import Alamofire class PlayerViewController: UIViewController, JukeboxDelegate { var podcastData = [PodcastObject]() var jukebox : Jukebox! var indexPlayerz: Int! var jukeboxItems = [JukeboxItem]() @IBOutlet weak var slider: UISlider! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var replayButton: UIButton! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var currentTimeLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var centerContainer: UIView! @IBOutlet weak var downloadBtn: UIBarButtonItem! override var canBecomeFirstResponder: Bool { return true } override func viewDidLoad() { super.viewDidLoad() configureUI() UIApplication.shared.beginReceivingRemoteControlEvents() self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false if DOWNLOAD_PODCAST && SHOW_PODCAST{ } else { self.navigationItem.rightBarButtonItem = nil ; } } func configureUI () { resetUI() slider.setThumbImage(UIImage(named: "sliderThumb"), for: UIControl.State()) } override func viewWillDisappear(_ animated: Bool) { if (self.isMovingFromParent){ jukebox.stop() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] navigationController?.navigationBar.tintColor = .white jukeboxItems.removeAll() for i in 0..<self.podcastData.count { let mix = self.podcastData[i] print(mix.file) let trackUrl = mix.file jukeboxItems.append(JukeboxItem(URL: trackUrl!)) } jukebox = Jukebox(delegate: self, items:jukeboxItems)! let radio = RadioViewController() radio.radioStop() jukebox.play(atIndex: indexPlayerz) updateArtistLabel() } func updateArtistLabel(){ let item = jukebox.currentItem let title = String(format:"%@",(item?.URL.lastPathComponent)!) let newString = title.replacingOccurrences(of: ".mp3", with: "", options: .literal, range: nil) let newString1 = newString.replacingOccurrences(of: "_", with: " ", options: .literal, range: nil) titleLabel.text = newString1 } func jukeboxDidLoadItem(_ jukebox: Jukebox, item: JukeboxItem) { print("Jukebox did load: \(item.URL.lastPathComponent)") } func jukeboxPlaybackProgressDidChange(_ jukebox: Jukebox) { if let currentTime = jukebox.currentItem?.currentTime, let duration = jukebox.currentItem?.meta.duration { let value = Float(currentTime / duration) slider.value = value populateLabelWithTime(currentTimeLabel, time: currentTime) populateLabelWithTime(durationLabel, time: duration) } else { resetUI() } } func jukeboxStateDidChange(_ jukebox: Jukebox) { UIView.animate(withDuration: 0.3, animations: { () -> Void in self.playPauseButton.alpha = jukebox.state == .loading ? 0 : 1 self.playPauseButton.isEnabled = jukebox.state == .loading ? false : true }) if jukebox.state == .ready { playPauseButton.setImage(UIImage(named: "play-button.png"), for: UIControl.State()) } else if jukebox.state == .loading { playPauseButton.setImage(UIImage(named: "pause-button.png"), for: UIControl.State()) } else { let imageName: String switch jukebox.state { case .playing, .loading: imageName = "pause-button.png" case .paused, .failed, .ready: imageName = "play-button.png" } playPauseButton.setImage(UIImage(named: imageName), for: UIControl.State()) } } func jukeboxDidUpdateMetadata(_ jukebox: Jukebox, forItem: JukeboxItem) { print("Item updated:\n\(forItem)") } func populateLabelWithTime(_ label : UILabel, time: Double) { let minutes = Int(time / 60) let seconds = Int(time) - minutes * 60 label.text = String(format: "%02d", minutes) + ":" + String(format: "%02d", seconds) } func resetUI() { durationLabel.text = "00:00" currentTimeLabel.text = "00:00" slider.value = 0 } override func remoteControlReceived(with event: UIEvent?) { if event?.type == .remoteControl { switch event!.subtype { case .remoteControlPlay : jukebox.play() case .remoteControlPause : jukebox.pause() case .remoteControlNextTrack : jukebox.playNext() case .remoteControlPreviousTrack: jukebox.playPrevious() case .remoteControlTogglePlayPause: if jukebox.state == .playing { jukebox.pause() } else { jukebox.play() } default: break } } } @IBAction func progressSliderValueChanged() { if let duration = jukebox.currentItem?.meta.duration { jukebox.seek(toSecond: Int(Double(slider.value) * duration)) } } @IBAction func prevAction() { if let time = jukebox.currentItem?.currentTime, time > 5.0 || jukebox.playIndex == 0 { jukebox.replayCurrentItem() updateArtistLabel() } else { jukebox.playPrevious() updateArtistLabel() } } @IBAction func nextAction() { jukebox.playNext() updateArtistLabel() } @IBAction func playPauseAction() { switch jukebox.state { case .ready : jukebox.play(atIndex: 0) case .playing : jukebox.pause() case .paused : jukebox.play() default: jukebox.stop() } } func playsPayse(){ switch jukebox.state { case .ready : jukebox.play(atIndex: 0) case .playing : jukebox.pause() case .paused : jukebox.play() default: jukebox.stop() } } @IBAction func replayAction() { resetUI() jukebox.replay() } @IBAction func stopAction() { resetUI() jukebox.stop() } @IBAction func download(){ let trackUrl = jukebox.currentItem let track = trackUrl?.URL let name = track?.lastPathComponent let destination: DownloadRequest.DownloadFileDestination = { _, _ in var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // the name of the file here I kept is yourFileName with appended extension documentsURL.appendPathComponent(name!) return (documentsURL, [.removePreviousFile]) } Alamofire.download(track!, to: destination) .downloadProgress { progress in self.navigationController?.setProgress(Float(progress.fractionCompleted), animated: true) print("Download Progress: \(progress.fractionCompleted)") if (progress.fractionCompleted == 1){ self.navigationController?.finishProgress() } } .response { response in if response.destinationURL != nil { print(response.destinationURL!) } } } }
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { Hero } from '../../../models/hero'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-hero-form', standalone: true, imports: [FormsModule], templateUrl: './hero-form.component.html', styleUrl: './hero-form.component.scss' }) export class HeroFormComponent implements OnChanges{ @Output() onAddHero = new EventEmitter<Hero>(); @Input() hero: Hero = new Hero('',''); heroName = ''; heroDescription = ''; constructor() { } ngOnChanges(changes: SimpleChanges): void { this.hero.name ? this.heroName = this.hero.name : null; this.hero.description ? this.heroDescription = this.hero.description : null; } addHero() { this.onAddHero.emit(new Hero(this.heroName, this.heroDescription)); this.heroName = ''; this.heroDescription = ''; } }
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map, Observable, throwError } from 'rxjs'; import { IMaritalCountByState } from '../interfaces/imarital-count-by-state'; @Injectable({ providedIn: 'root' }) export class MaritalCountByStateService { constructor(private http: HttpClient) { } private url: string = "http://localhost:8080/api/marital_status/couples" getMaritalCount(): Observable<IMaritalCountByState[]> { // sample result: ["FL, 0.160220", "GA, 0.039402"] return this.http.get<String[]>(this.url).pipe(map(result => { let ret: IMaritalCountByState[] = result.map(x => { return { name: x.split(",")[0], value: Number(x.split(",")[1]) }; }); console.log(ret); return ret; }), catchError(this.handleError)); } private handleError(err: HttpErrorResponse) { let errorMessage = ''; if (err.error instanceof ErrorEvent) { errorMessage = `An error occured: ${err.error.message}`; } else { errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`; } return throwError(() => errorMessage); } }
<div> <!-- <p [style]=colorStyle>Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores, quia.</p> <input type="text" (keyup)="save($event)"> <input type="text" [(ngModel)]="twoway"> <p>{{twoway}}</p> --> <ol> <li *ngFor="let i of arr"> {{i}} </li> </ol> <table class="table table-striped"> <tr *ngFor="let i of names"> <td>{{i.fname}}</td> <td>{{i.lname}}</td> <td>{{i.age}}</td> </tr> </table> </div> <h1>{{nme}}</h1> <h1>{{values}}</h1> <input [(ngModel)]="nme"> <input (keyup)="onKey($event)"> <p>{{ values }}</p> <!-- <input type="text" (change)='save($event)'></input> --> <!-- <button (click) = "save($event)" value="Submit"></button> --> <input type="text" [(ngModel)]="str"> <h1>{{str}}</h1> <ol> <li *ngFor="let day of days">{{day}}</li> </ol> <div *ngIf="isValid"> <p>I am going to go</p> </div> <div *ngIf="!isValid"> <p>I am not going to go</p> </div> <div *ngFor="let student of students"> <span [ngStyle]="{'background-color':student.gender === 'female' ? 'red': 'green' }"> Name:{{student.name}}, Gender:{{student.gender}} </span> </div> <h1>Select Country</h1> <select (change)="SetDropValue($event)"> <option value=" "></option> <option value="In">In</option> <option value="Us">US</option> <option value="Uk">UK</option> </select> <h1>You Selected</h1> <div [ngSwitch]="dropValue"> <h2 *ngSwitchCase="'In'">India</h2> <h2 *ngSwitchCase="'Us'">USA</h2> <h2 *ngSwitchCase="'Uk'">United Kingdom</h2> </div>
#include "seqFileHandler.hpp" SeqFileHandler::SeqFileHandler() { this->filename = ""; this->success = false; this->sequencesInMemory = false; } SeqFileHandler::SeqFileHandler(std::string filename) { this->sequencesInMemory = false; setFileName(filename); createIndex(); if (!this->success) std::cout << "Could not build index!" << std::endl; if (!openFile()) throw std::runtime_error("Could not open sequence file / index."); } void SeqFileHandler::setFileName(std::string filename) { this->filename = filename; } void SeqFileHandler::createIndex() { std::string faiFileName = this->filename + ".fai"; this->success = seqan::build(this->faiIndex, filename.c_str(), faiFileName.c_str()); seqan::save(faiIndex); } bool SeqFileHandler::openFile() { return seqan::open(this->faiIndex, this->filename.c_str()); } int SeqFileHandler::getIndex(std::string rName) { int idx = -1; if (!seqan::getIdByName(idx, this->faiIndex, rName)) { idx = -1; std::cout << "ERROR: FaiIndex has no entry for " + rName << std::endl; } return idx; } seqan::Dna5String SeqFileHandler::getBaseAtPosition(std::string rName, int position) { seqan::Dna5String sequence; if (position >= getChrLength(rName)) return sequence; if (this->sequencesInMemory && this->chromosomeSequences.find(rName) != this->chromosomeSequences.end()) { if (position < (int) seqan::length(this->chromosomeSequences[rName][position])) sequence = this->chromosomeSequences[rName][position]; } else { int idx = getIndex(rName); if (idx < 0) return sequence; seqan::readRegion(sequence, this->faiIndex, idx, position + 1, position + 2); } return sequence; } seqan::Dna5String SeqFileHandler::getRegionSequence(std::string rName, int begin, int end) { seqan::Dna5String sequence; if (this->sequencesInMemory && this->chromosomeSequences.find(rName) != this->chromosomeSequences.end()) { for (int i = begin; i <= end; ++i) if (i < (int) seqan::length(this->chromosomeSequences[rName])) seqan::append(sequence, this->chromosomeSequences[rName][i]); else break; } else { int idx = getIndex(rName); if (idx < 0) return sequence; ++begin; ++end; end = std::min(end + 1, getChrLength(rName)); seqan::readRegion(sequence, this->faiIndex, idx, begin, end); } return sequence; } seqan::Dna5String SeqFileHandler::getChromosomeSequence(std::string rName) { seqan::Dna5String sequence; if (this->sequencesInMemory && this->chromosomeSequences.find(rName) != this->chromosomeSequences.end()) { return this->chromosomeSequences[rName]; } else { int idx = getIndex(rName); if (idx < 0) return sequence; seqan::readSequence(sequence, this->faiIndex, idx); } return sequence; } void SeqFileHandler::writeSequencesToFile(seqan::String<seqan::CharString>ids, seqan::String<seqan::Dna5String> sequences, std::string outFileName) { seqan::SeqFileOut outputFile(outFileName.c_str()); if (seqan::isOpen(outputFile)) { try { #pragma omp critical writeRecords(outputFile, ids, sequences); } catch (seqan::Exception const & e) { std::cout << "ERROR: " << e.what() << std::endl; } seqan::close(outputFile); } else { std::cerr << "Could not open output file " << outFileName << std::endl; } } bool SeqFileHandler::containsChrSequence(std::string cName) { int idx = getIndex(cName); if (idx == -1) return false; return true; } int SeqFileHandler::getChrLength(std::string cName) { int idx = getIndex(cName); if (idx != -1) return seqan::sequenceLength(this->faiIndex, idx); return 0; } void SeqFileHandler::open(std::string filename) { setFileName(filename); createIndex(); if (!this->success) std::cout << "Could not build index!" << std::endl; if (!openFile()) { this->success = false; throw std::runtime_error("Could not open sequence file / index."); } else { this->success = true; } } bool SeqFileHandler::isOpen() { return this->success; } void SeqFileHandler::close() { if (seqan::isOpen(this->seqFileIn)) seqan::close(this->seqFileIn); } std::unordered_map<std::string, int> SeqFileHandler::getSequenceLengths() { std::unordered_map<std::string, int> seqLens; if (isOpen()) for (uint64_t i = 0; i < seqan::numSeqs(this->faiIndex); ++i) seqLens[std::string(seqan::toCString(seqan::sequenceName(this->faiIndex, i)))] = seqan::sequenceLength(this->faiIndex, i); return seqLens; } void SeqFileHandler::loadChromosomeSequences() { for (auto it : getSequenceLengths()) if (it.first.size() < 6) this->chromosomeSequences[it.first] = getChromosomeSequence(it.first); this->sequencesInMemory = true; } bool SeqFileHandler::hasSequencesInMemory() { return this->sequencesInMemory; }
import pandas as pd import numpy import matplotlib.pyplot as plt from numpy.fft import fft, fftfreq, rfft from scipy import signal filename = "IMUData.csv" plt.rcParams["figure.autolayout"] = True df = pd.read_csv(filename) Time = df['Time'] IMUAccY = df['AccY'] IMUAccX = df['AccX'] IMUAccZ = df['AccZ'] IMUGyroX = df['GyroX'] IMUGyroY = df['GyroY'] IMUGyroZ = df['GyroZ'] Time_diff = (df['Time'].iloc[-1] - df['Time'].iloc[0]) SAMPLE_TIME = (Time_diff / len(Time)) / 1000 SAMPLE_FREQ = numpy.round(1000 * len(Time) / Time_diff) SENSE = 0.019 print(f"Sample Time: {SAMPLE_TIME} at Sample Freq: {SAMPLE_FREQ}") class DataPreparation: def __init__(self): self.AccX_Trimmed = None self.AccY_Trimmed = None self.AccZ_Trimmed = None self.SMV_Trimmed = None self.Jerk_Trimmed = None self.GyroX_Trimmed = None self.GyroY_Trimmed = None self.GyroZ_Trimmed = None self.AccX = self.ButterFilter(IMUAccX) self.AccY = self.ButterFilter(IMUAccY) self.AccZ = self.ButterFilter(IMUAccZ) self.GyroX = IMUGyroX[400:] self.GyroY = IMUGyroY[400:] self.GyroZ = IMUGyroZ[400:] self.SMV = self.SMV_Calc() self.jerk = [] self.jerk_roll = [] self.jerk_calc() self.SMV_roll = [] self.Sample_Freq = SAMPLE_FREQ self.FilteredLength = len(self.AccX) self.time_axis = numpy.arange(0, (self.FilteredLength / SAMPLE_FREQ), 1 / SAMPLE_FREQ) self.SMV_Window() self.rolling_axis = numpy.arange(0, self.FilteredLength / SAMPLE_FREQ, (self.FilteredLength / SAMPLE_FREQ) / len( self.SMV_roll)) self.grapher() def ButterFilter(self, RawData): # Butterworth Function Filter to remove gravity sos = signal.butter(1, 0.25, 'hp', fs=SAMPLE_FREQ, output='sos') ButterData = signal.sosfilt(sos, RawData) return ButterData[400:] def jerk_calc(self): self.jerk = numpy.gradient(self.SMV) self.jerk_roll = numpy.convolve(self.jerk, numpy.ones(20), 'same') / 20 def SMV_Calc(self): # Calculates SMV from Acceleratio Data signal_sum = pow(self.AccX, 2) + pow(self.AccY, 2) + pow(self.AccZ, 2) return numpy.sqrt(signal_sum) def grapher(self): # Graphs Acceleration and SMV print(f"Acc = {len(self.AccX)} and Time {len(self.time_axis)}") if len(self.AccX) < len(self.time_axis): self.time_axis = self.time_axis[:-1] print(f"Acc = {len(self.AccX)} and Time {len(self.time_axis)}") if len(self.AccX) == len(self.time_axis): plt.subplot(3, 1, 1) plt.plot(self.time_axis, self.AccX, label="X") plt.plot(self.time_axis, self.AccY, label="Y") plt.plot(self.time_axis, self.AccZ, label="Z") plt.ylim(-1,1) plt.xlabel("Time (s)") plt.ylabel("Acceleration (g)") plt.title("Acceleration (X,Y,Z)") plt.legend(loc=1) plt.subplot(3, 1, 2) plt.plot(self.time_axis, self.SMV, label='SMV') plt.plot(self.time_axis, self.SMV_roll, label="SMV Rolling") plt.legend(loc=1) plt.xlabel("Time (s)") plt.ylabel("Acceleration (g)") plt.title("Acceleration (SMV)") plt.ylim(-0.2, 1) plt.subplot(3, 1, 3) # plt.plot(self.time_axis, self.jerk, label='Jerk') plt.plot(self.time_axis, self.jerk_roll, label="Jerk") plt.legend(loc=1) plt.ylim(-0.03, 0.03) plt.xlabel("Time (s)") plt.ylabel("Jerk (g/s)") plt.title("Jerk (SMV)") plt.legend(loc=1) plt.show() def SMV_Window(self): # Creates Rolling Average for SMV self.SMV_roll = numpy.convolve(self.SMV, numpy.ones(20), 'same') / 20 self.movement_filter() def movement_filter( self): # Detects when movement has started or stopped based on previous values (of rolling SMV) at a # given threshold start = [] # used for if there are multiple start stops in a movement pattern stop = [] for i in range(4, len(self.SMV_roll)): if (self.SMV_roll[i] > SENSE > self.SMV_roll[i - 4] and self.SMV_roll[i - 2] > SENSE and self.SMV_roll[i - 1] > SENSE and self.SMV_roll[i - 3] > SENSE): print(f"Started movement at {i * SAMPLE_TIME} : {i}") start.append(i) elif self.SMV_roll[i] < SENSE < self.SMV_roll[i - 4] and self.SMV_roll[i - 2] < SENSE and self.SMV_roll[i - 1] < SENSE and self.SMV_roll[i - 3] < SENSE: print(f"Stopped movement at {i * SAMPLE_TIME} : {i}") stop.append(i) stop.append(len(self.SMV_roll)) if len(start) < 1: start.append(0) value = 0 time_stamp = 0 for j in range(len(start)-1): print(j) if (stop[j-1]-start[j-1]) > value: value = stop[j-1]-start[j-1] time_stamp = j-1 print(time_stamp) self.SMV_Trimmed = self.SMV[start[time_stamp]:stop[time_stamp]] self.AccX_Trimmed = self.AccX[start[time_stamp]:stop[time_stamp]] self.AccY_Trimmed = self.AccY[start[time_stamp]:stop[time_stamp]] self.AccZ_Trimmed = self.AccZ[start[time_stamp]:stop[time_stamp]] self.Jerk_Trimmed = self.jerk_roll[start[time_stamp]:stop[time_stamp]] self.GyroX_Trimmed = self.GyroX[start[time_stamp]:stop[time_stamp]] self.GyroY_Trimmed = self.GyroY[start[time_stamp]:stop[time_stamp]] self.GyroZ_Trimmed = self.GyroZ[start[time_stamp]:stop[time_stamp]] class Features: def __init__(self, TrimmedData): self.AccX = TrimmedData.AccX_Trimmed self.AccY = TrimmedData.AccY_Trimmed self.AccZ = TrimmedData.AccZ_Trimmed self.SMV = TrimmedData.SMV_Trimmed self.Jerk = TrimmedData.Jerk_Trimmed self.GyroX = TrimmedData.GyroX_Trimmed self.GyroY = TrimmedData.GyroY_Trimmed self.GyroZ = TrimmedData.GyroZ_Trimmed self.time = len(self.SMV) * SAMPLE_TIME self.trimmed_axis = numpy.arange(0, len(self.AccX) / SAMPLE_FREQ, 1 / SAMPLE_FREQ) self.graph_trimmed() self.FFTFreq = 0 self.x_features = {} self.y_features = {} self.z_features = {} self.SMV_features = {} self.data_extraction(self.SMV, self.SMV_features) self.data_extraction(self.AccZ, self.z_features) self.data_extraction(self.AccY, self.y_features) self.data_extraction(self.AccX, self.x_features) self.frequency_calc() self.freq_calc_2() self.output = [self.x_features['max'], self.x_features['min'], self.x_features['minmax'], self.x_features['peak'], self.x_features['std'], self.x_features['rms'], self.x_features['var'], self.y_features['max'], self.y_features['min'], self.y_features['minmax'], self.y_features['peak'], self.y_features['std'], self.y_features['rms'], self.y_features['var'], self.z_features['max'], self.z_features['min'], self.z_features['minmax'], self.z_features['peak'], self.z_features['std'], self.z_features['rms'], self.z_features['var'], self.SMV_features['max'], self.SMV_features['min'], self.SMV_features['minmax'], self.SMV_features['peak'], self.SMV_features['std'], self.SMV_features['rms'], self.SMV_features['var'], self.FFTFreq] self.output2 = {} self.dictionary_combine() def graph_trimmed(self): # graphs the sections that have been trimmed by the movement filter if (len(self.trimmed_axis)) > len(self.AccX): last = len(self.trimmed_axis) - 1 self.trimmed_axis = self.trimmed_axis[:last] plt.subplot(3, 1, 1) plt.plot(self.trimmed_axis, self.AccX, label="X") plt.plot(self.trimmed_axis, self.AccY, label="Y") plt.plot(self.trimmed_axis, self.AccZ, label="Z") plt.ylim(-1, 1) plt.xlabel("Time (s)") plt.ylabel("Acceleration (g)") plt.title("Acceleration (X, Y, Z)") plt.legend(loc=1) plt.subplot(3, 1, 2) plt.plot(self.trimmed_axis, self.SMV, label='SMV') plt.legend(loc=1) plt.ylim(-0.2, 1.5) plt.xlabel("Time (s)") plt.ylabel("Acceleration (g)") plt.title("Acceleration (SMV)") plt.subplot(3, 1, 3) plt.plot(self.trimmed_axis, self.Jerk, label='SMV') plt.legend(loc=1) plt.ylim(-0.03, 0.03) plt.xlabel("Time (s)") plt.ylabel("Jerk (g/s)") plt.title("Jerk (SMV)") plt.show() def sliding_windows(self, data): # Creates Sliding Windows from Filtered and Sliced Array i = 0 window_array = [] while i <= len(data): window_small = data[i:i + 20] window_array.append(window_small) i += 10 return window_array def minmax_spread(self, array, dictionary): # Returns Min-Max Data of an Array max_data = max(array) min_data = min(array) minmax_data = max_data - min_data peak_data = max(max_data, min_data) rms_data = numpy.sqrt(numpy.mean(array ** 2)) std_data = numpy.nanstd(array) var_data = numpy.nanvar(array) dictionary['max'] = max_data dictionary['min'] = min_data dictionary['minmax'] = minmax_data dictionary['peak'] = peak_data dictionary['rms'] = rms_data dictionary['std'] = std_data dictionary['var'] = var_data def data_extraction(self, array, dictionary): self.minmax_spread(array, dictionary) print(dictionary) def dictionary_combine(self): axis = [self.x_features, self.y_features, self.z_features, self.SMV_features] for i in range(len(axis)): for keys, values in axis[i].items(): if i == 0: label = 'X' elif i == 1: label = 'Y' elif i == 2: label = 'Z' elif i == 3: label = 'SMV' print(f"{label}{keys} : {values}") self.output2[f"{label}{keys}"] = values self.output2['Freq'] = self.FFTFreq def features_graph(self): plt.subplot(3, 1, 1) plt.plot(self.x_features['rms'], label="X") plt.plot(self.y_features['rms'], label="Y") plt.plot(self.z_features['rms'], label="Z") plt.plot(self.SMV_features['rms'], label="SMV") plt.ylim(-0.1, 0.5) plt.title("RMS of Data") plt.legend(loc=1) plt.subplot(3, 1, 2) plt.plot(self.x_features['var'], label="X") plt.plot(self.y_features['var'], label="Y") plt.plot(self.z_features['var'], label="Z") plt.plot(self.SMV_features['var'], label="SMV") plt.ylim(-0.005, 0.03) plt.title("VAR of Data") plt.legend(loc=1) plt.subplot(3, 1, 3) plt.plot(self.x_features['std'], label="X") plt.plot(self.y_features['std'], label="Y") plt.plot(self.z_features['std'], label="Z") plt.plot(self.SMV_features['std'], label="SMV") plt.ylim(-0.05, 0.15) plt.title("STD of Data") plt.legend(loc=1) plt.show() def features_graph2(self): plt.subplot(4, 1, 1) plt.plot(self.x_features['max'], label="X") plt.plot(self.y_features['max'], label="Y") plt.plot(self.z_features['max'], label="Z") plt.plot(self.SMV_features['max'], label="SMV") plt.ylim(-1, 1.5) plt.title("Max of Data") plt.legend(loc=1) plt.subplot(4, 1, 2) plt.plot(self.x_features['min'], label="X") plt.plot(self.y_features['min'], label="Y") plt.plot(self.z_features['min'], label="Z") plt.plot(self.SMV_features['min'], label="SMV") plt.ylim(-1, 1) plt.title("Min of Data") plt.legend(loc=1) plt.subplot(4, 1, 3) plt.plot(self.x_features['minmax'], label="X") plt.plot(self.y_features['minmax'], label="Y") plt.plot(self.z_features['minmax'], label="Z") plt.plot(self.SMV_features['minmax'], label="SMV") plt.ylim(-0.2, 1.5) plt.title("MinMax of Data") plt.legend(loc=1) plt.subplot(4, 1, 4) plt.plot(self.x_features['peak'], label="X") plt.plot(self.y_features['peak'], label="Y") plt.plot(self.z_features['peak'], label="Z") plt.plot(self.SMV_features['peak'], label="SMV") plt.ylim(-0.2, 1) plt.title("Peak of Data") plt.legend(loc=1) plt.show() def frequency_calc(self): fft_array = [] mean = numpy.mean(self.SMV) for i in self.SMV: fft_array.append(i - mean) fft_out = fft(fft_array) fft_freq = fftfreq(len(fft_out), 1 / SAMPLE_FREQ) x_freq = numpy.abs(fft_freq) y_fft = numpy.abs(fft_out) # Plotting IMU angle through Time # Plotting Frequency Amplitude (FFT) plt.subplot(1, 1, 1) plt.plot(x_freq, y_fft, 'b', label = 'mean smv') plt.xlabel("Frequency (Hz)") plt.ylabel("Frequency Amplitude") plt.xlim(right=20) plt.xlim(left=-1) # Prints the dominate frequency y_max = numpy.argmax(y_fft) x_max = x_freq[y_max] print(f"Frequency is {x_max}") self.FFTFreq = x_max def freq_calc_2(self): fft_out = fft(self.AccZ) fft_freq = fftfreq(len(fft_out), 1 / SAMPLE_FREQ) x_freq = numpy.abs(fft_freq) y_fft = numpy.abs(fft_out) # Plotting IMU angle through Time # Plotting Frequency Amplitude (FFT) plt.subplot(1, 1, 1) plt.plot(x_freq, y_fft, 'r', label = "normal single axis") plt.xlabel("Frequency (Hz)") plt.ylabel("Frequency Amplitude") plt.xlim(right=20) plt.xlim(left=-1) plt.legend() plt.show()
using Birds.Interfaces; using Birds.Species; namespace Birds; class Program { static void Main(string[] args) { List<Bird> birds = new List<Bird>(); birds.Add(new Crow()); birds.Add(new Duck()); birds.Add(new Penguin()); birds.Add(new Thrush()); foreach (Bird bird in birds) { Console.WriteLine("-------------------------------------"); Console.WriteLine(bird); Console.WriteLine("-------------------------------------"); if (bird is IFly flybird) { flybird.Fly(); } if (bird is IFloat floatbird) { floatbird.Float(); } if (bird is INoise noisebird) { noisebird.Noise(); } if (bird is ISwim swimbird) { swimbird.Swim(); } Console.WriteLine("-------------------------------------\n"); } } }
import React, {useEffect, useState} from 'react'; import {observer} from "mobx-react-lite"; import {Menu} from "../common/menu"; import {Container} from "react-bootstrap"; import {ARTWORK_ROUTE_LESS_ID, CREATION_ROUTE_LESS_ID, MAIN_ROUTE, PROFILE_ROUTE_LESS_ID} from "../../utils/consts"; import UserLogo from "../common/images/UserLogo.png"; import {useNavigate} from "react-router-dom"; import {getAllUsers} from "../../http/userApi"; import {getAllProjects, getAllProjectsUsers, remove} from "../../http/projectApi"; import {Project} from "../providers/CanvasContextProvider"; import Dummy from "../common/images/vorona.png"; const MainPage = observer(() => { const navigate = useNavigate() const [users, setUsers] = useState<{ email: string, nickname: string }[]>([]) const [projects, setProjects] = useState<Project[]>([]); const [previews, setPreviews] = useState<{preview: string, gif: string[], projectId: number}[]>([]); useEffect(() => { getAllUsers().then(data => { setUsers(data) }) }, []) useEffect(() => { getAllProjectsUsers().then(data => { setProjects(data.projects) setPreviews(data.previews) }).catch(error => { console.log(error) navigate(MAIN_ROUTE) }) }, []) return ( <div style={{backgroundColor: "#DFDFDF"}}> <Menu/> <Container fluid style={{textAlign: "center", marginTop: "20px"}}> <div className={"Text-Header2"} style={{textAlign: "center"}}> Authors </div> <div style={{ display: "inline-grid", gridTemplateColumns: `repeat(${Math.max(10,users.length)},1fr)`, width: "100%", overflow: "auto" }} > { users.map((it, index) => <div style={{ backgroundColor: "#EFEFEF", width: "250px", height: "85px", borderRadius: "5%", marginBottom: "20px", border: "4px solid black", marginRight: "10px", textAlign: "center", }} key={index} > <Container fluid style={{marginBottom: "10px", textAlign: "center"}}> <div className={"Text-Header2 ms-auto"} style={{ textAlign: "right", alignItems: "center", marginTop: "10px", cursor: "pointer", }} onClick={() => { navigate(PROFILE_ROUTE_LESS_ID + it.nickname) } } > {(it.nickname).substring(0, 10)} <img alt="" src={UserLogo} width="48" height="48" className="d-inline-block align-top" style={{ transform: "scaleX(-1)", backgroundColor: "#000", borderRadius: "25px", marginLeft: "10px" }} /> </div> </Container> </div>) } </div> <div className={"Text-Header2"} style={{textAlign: "center"}}> Projects </div> <div style={{ display: "inline-grid", gridTemplateColumns: `repeat(6,1fr)`, width: "100%", marginTop: "20px" }} > { projects.filter(it => it.published).map((it, index) => <div style={{ backgroundColor: "#EFEFEF", width: "90%", borderRadius: "5%", aspectRatio: 1, marginBottom: "20px", border: "4px solid black", }} key={index} > <Container fluid style={{marginBottom: "10px", textAlign: "center"}}> <div className={"Text-Header2"} style={{fontWeight: "bold"}}>{it.name.substring(0, 15)}</div> <div className={"Text-Regular"}>{it.description.substring(0, 25)}</div> <img width={"100%"} src={`${previews.find(prev => prev.projectId === it.index )?.preview}`} style={{aspectRatio: 1, cursor: "pointer"}} onClick={() => { navigate(ARTWORK_ROUTE_LESS_ID + it.index) } }/> </Container> </div>) } </div> </Container> </div>) }) export default MainPage;
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ThirdPersonMPProjectile.generated.h" UCLASS() class THIRDPERSONMP_API AThirdPersonMPProjectile : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AThirdPersonMPProjectile(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; UFUNCTION(Category="Projectile") void OnProjectileImpact(UPrimitiveComponent* hitComponent,AActor* OtherActor, UPrimitiveComponent* OtherComponent,FVector NormalImpulse, const FHitResult& Hit); public: // Called every frame virtual void Tick(float DeltaTime) override; // Sphere component used to test collision UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") class USphereComponent* SphereComponent; // Static Mesh used to provide a visual representation of the object UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") class UStaticMeshComponent* StaticMesh; // Movement component for handling projectile movement UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") class UProjectileMovementComponent* ProjectileMovementComponent; // Particle used when the projectile impacts against another object and explodes UPROPERTY(EditAnywhere, Category="Effects") class UParticleSystem* ExplosionEffect; // The damage type and damage that will be done by this projectile UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Damage") TSubclassOf<class UDamageType> DamageType; // The damage delta by this projectile. UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Damage") float Damage; virtual void Destroyed() override; };
package kass.concurrente.modelo.cuchillo; /** * Clase que modela un cuchillo de cerámica. * @author Emmanuel Delgado * @version 1.1 */ public class CuchilloCeramica extends CuchilloDecorator{ /** * Constructor que recibe un cuchillo para crear * un cuchillo base. * @param cuchillo El cuchillo que se recibe. */ public CuchilloCeramica(Cuchillo cuchillo){ super(cuchillo); } /** * Devuelve el tiempo que se reduce al usar este cuchillo * @return el tiempo que se reduce la cocción. */ @Override public int corta(){ return 2; } }
from typing import Optional, Dict, Iterator, Union, Any from dlt.common import jsonpath from .client import RESTClient # noqa: F401 from .client import PageData from .auth import AuthConfigBase from .paginators import BasePaginator from .typing import HTTPMethodBasic, Hooks def paginate( url: str, method: HTTPMethodBasic = "GET", headers: Optional[Dict[str, str]] = None, params: Optional[Dict[str, Any]] = None, json: Optional[Dict[str, Any]] = None, auth: AuthConfigBase = None, paginator: Optional[BasePaginator] = None, data_selector: Optional[jsonpath.TJsonPath] = None, hooks: Optional[Hooks] = None, ) -> Iterator[PageData[Any]]: """ Paginate over a REST API endpoint. Args: url: URL to paginate over. **kwargs: Keyword arguments to pass to `RESTClient.paginate`. Returns: Iterator[Page]: Iterator over pages. """ client = RESTClient( base_url=url, headers=headers, ) return client.paginate( path="", method=method, params=params, json=json, auth=auth, paginator=paginator, data_selector=data_selector, hooks=hooks, )
import React, { useState, useEffect } from 'react'; import { useHistory } from 'react-router-dom'; import ChessBoard from '../components/ChessBoard'; import Header from '../components/Header'; import SideBar from '../components/SideBar'; import './styles/ProfilePage.css'; const ProfilePage = () => { const history = useHistory(); const [userBoards, setUserBoards] = useState([]); const [username, setUsername] = useState(''); const [editingBoardId, setEditingBoardId] = useState(null); const [newComment, setNewComment] = useState(''); const navigateToHome = () => { history.push('/'); }; const handleLogout = () => { localStorage.removeItem('jwtToken'); history.push('/'); }; const handleEdit = (boardId, comment) => { setEditingBoardId(boardId); setNewComment(comment || ''); }; const handleSave = async () => { const token = localStorage.getItem('jwtToken'); const response = await fetch('http://localhost:5000/api/boards/addComment', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, body: JSON.stringify({ boardId: editingBoardId, comment: newComment, }), }); const data = await response.json(); if (data.success) { const updatedBoards = userBoards.map((board) => board._id === editingBoardId ? { ...board, comment: newComment } : board ); setUserBoards(updatedBoards); setEditingBoardId(null); setNewComment(''); } else { // Handle error } }; const handleCancel = () => { setEditingBoardId(null); setNewComment(''); }; const handleDelete = async (boardId) => { const token = localStorage.getItem('jwtToken'); const response = await fetch(`http://localhost:5000/api/boards/delete/${boardId}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, }); const data = await response.json(); if (data.success) { const updatedBoards = userBoards.filter((board) => board._id !== boardId); setUserBoards(updatedBoards); } else { // Handle error } }; useEffect(() => { const fetchUserData = async () => { const token = localStorage.getItem('jwtToken'); const responseBoards = await fetch('http://localhost:5000/api/boards/load', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, }); const dataBoards = await responseBoards.json(); setUserBoards(dataBoards); const responseUsername = await fetch('http://localhost:5000/api/users/username', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, }); const dataUsername = await responseUsername.json(); setUsername(dataUsername.username); }; fetchUserData(); }, []); return ( <div className="ProfilePage"> <Header /> <SideBar /> <div className="ProfileTitle"> <h1>{username}'s Profile</h1> </div> <div className="ReturnButtonsContainer"> <button className="ReturnButtons" onClick={navigateToHome}>Home</button> <button className="ReturnButtons" onClick={handleLogout}>Logout</button> </div> <div className="SavedBoardsView"> {userBoards.map((board, index) => ( <div className="boardContainer" key={board._id}> <h2>Board {index + 1}</h2> <button className="DeleteButton" onClick={() => handleDelete(board._id)}>Delete</button> <ChessBoard whitePieces={board.configuration} /> <textarea className="commentBox" readOnly={editingBoardId !== board._id} value={editingBoardId === board._id ? newComment : board.comment || ''} onChange={(e) => setNewComment(e.target.value)} /> {editingBoardId === board._id ? ( <> <div> <button className="EditButton" onClick={handleSave}>Save</button> <button className="EditButton" onClick={handleCancel}>Cancel</button> </div> </> ) : ( <button className="EditButton" onClick={() => handleEdit(board._id, board.comment)}>Edit Comment</button> )} </div> ))} </div> </div> ); }; export default ProfilePage;
import "./App.css"; import "bulma/css/bulma.min.css"; import { Box, Columns, Heading, Table, Form, Button, Icon } from "react-bulma-components"; import { useEffect, useState } from "react"; import { deleteContact, getAllContacts, getContact, writeContactData } from "./firebase/firebase"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faXmark, faPenToSquare, faUser, faPhone } from "@fortawesome/free-solid-svg-icons"; function App() { const [contacts, setContacts] = useState([]); const [loading, setLoading] = useState(true); const [editContact, setEditContact] = useState(false); const handleSubmit = (e) => { e.preventDefault(); const { username, phone, gender } = e.target; const id = editContact.id || Date.now(); if (editContact) setEditContact(false); writeContactData(id, username.value, phone.value, gender.value); e.target.reset(); getAllContacts(setContacts); }; const handleDelete = (e) => { const id = e.currentTarget.title; deleteContact(id); getAllContacts(setContacts); }; const handleEdit = (e) => { const id = e.currentTarget.title; getContact(id, setEditContact); }; useEffect(() => { getAllContacts(setContacts, setLoading); }, []); //*TODO fix gender not being selected on edit. return ( <Columns id="content"> <Columns.Column size={"one-quarter"} id="left"> <Box textAlign={"center"}> <Heading>FireContact App</Heading> </Box> <Box textAlign={"center"}> <Heading size={4}>Add Contact</Heading> </Box> <Box> <form onSubmit={handleSubmit}> <Form.Field> <Form.Label>Username</Form.Label> <Form.Control> <Form.Input type={"text"} placeholder="Username" required name="username" defaultValue={editContact ? editContact.username : ""} /> <Icon align="left" size="small"> <FontAwesomeIcon icon={faUser} /> </Icon> </Form.Control> </Form.Field> <Form.Field> <Form.Control> <Form.Input type={"tel"} placeholder="Phone Number" required name="phone" defaultValue={editContact ? editContact.phone : ""} /> <Icon align="left" size="small"> <FontAwesomeIcon icon={faPhone} /> </Icon> </Form.Control> </Form.Field> <Form.Field> <Form.Control> <Form.Select name="gender" required fullwidth defaultValue={editContact ? editContact.gender : ""} > <option value="" disabled> Gender </option> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Other">Other</option> </Form.Select> </Form.Control> </Form.Field> <Button.Group> <Button color="link" type="submit" fullwidth> Add </Button> </Button.Group> </form> </Box> </Columns.Column> <Columns.Column size={"half"} id="right"> <Box textAlign={"center"}> <Heading>Contacts</Heading> </Box> <Box> <Table size="fullwidth" textAlign="center"> <thead> <tr> <th>Username</th> <th>Phone Number</th> <th>Gender</th> <th>Delete</th> <th>Edit</th> </tr> </thead> <tbody> {Boolean(contacts.length) ? ( contacts.map((contact) => { return ( <tr key={contact.id}> <td>{contact.username}</td> <td>{contact.phone}</td> <td>{contact.gender}</td> <td> <Button size={"small"} text onClick={handleDelete} title={contact.id} > <Icon color={"danger"}> <FontAwesomeIcon icon={faXmark} /> </Icon> </Button> </td> <td> <Button size={"small"} text onClick={handleEdit} title={contact.id} > <Icon color={"success"}> <FontAwesomeIcon icon={faPenToSquare} /> </Icon> </Button> </td> </tr> ); }) ) : ( <tr> {loading ? ( <td colSpan={5}>Loading...</td> ) : ( <td colSpan={5}>Nothing to show here...</td> )} </tr> )} </tbody> </Table> </Box> </Columns.Column> </Columns> ); } export default App;
import { observable, action, computed } from 'mobx'; import PropTypes from 'prop-types'; class Restaurants { // Locations @computed get getLocations() { return this.locations; } @observable locations = [ { id: 1, name: 'Raffy Terrace Bar', desc: 'Raffy for most of you is an association for something delicious. Whether it is ice cream on the showcases all over the country or the dishes in our restaurants we always try not to disappoint you. Raffy for one year became an emblematic place in the center of Sofia, and only because he listens daily to the needs of his guests. The pleasant environment, the good food and service, the constant renovation of the interior and the menu and all at an affordable price quickly won the sympathy of Sofia residents. Now we are introducing our new Raffy food & music project. Meals are served until 22:30 in the evening, and from the morning you can have a cup of coffee on the panoramic terrace above Vitoshka. A great place for a party, and you already know our handwriting. Always the best for the best.', photo: '../../assets/restaurants/raffy.jpg' }, { id: 2, name: 'Spaghetti Company', desc: 'Founded in 1999, Spaghetti Company has become established as an oasis of fine Italian fare. The restaurant has a unique atmosphere, combining modern design and classic elements. We are dedicated to combining the fine traditions of Italian cuisine and Bulgarian hospitality. Behind the scenes is chef Marco Luchiari, our Italian food expert and advisor. Twice a year he creates delicious additions to the main menu, providing our guests with new and inspiring offerings from the Italian kitchen. All our main products and ingredients have an authentic Italian origin. You are sure to love the experience of superb service and a masterful Italian menu in a trendy setting. A hot spot for lunch and dinner, Spaghetti Company is a not to be missed venue in Sofia.', photo: '../../assets/restaurants/spaghettikitchen.jpg' }, { id: 3, name: 'La Bocca', desc: 'La Bocca pizzeria was born of our passion for good nutrition - an unique product represented by a simple and stylish concept. We offer three basic high quality products - ITALIAN PIZZA, FRESH PASTA, FRESH BIG SALADS. Our kitchen is opened to customers and everything is prepared in front of them - one of the reasons we are so attractive. Pizza dough is made every day. With the help of our Italian partners who deliver flour from Italy especially for us we have achieved a perfect harmony between the ingredients. We use high quality Italian products to garnish the pizzas and the vegetables in our salads are the best on the market.', photo: '../../assets/restaurants/labocca.jpg' }, { id: 4, name: 'BMS Cuisine', desc: '"BMS Bulgarian Cuisine" is the largest chain in Bulgaria offering cooked specialties from traditional Bulgarian cuisine. We are among the first in the country to focus our efforts and activities on healthy eating. Every day we take care of our clients to taste delicious, fresh, freshly prepared soups, salads, meat and unsweetened specialties, trimmings, sauces, desserts, soft drinks and low-alcohol drinks. With us you will always be served politely. With our positive and friendly attitude, our employees will make you feel comfortable and enjoyable.', photo: '../../assets/restaurants/bms.jpg' }, { id: 5, name: 'Nordsee', desc: 'Nordsee is a German fast-food restaurant chain specialising in seafood. In addition to selling raw and smoked seafood, the company also sells a wide variety of meals and products prepared from seafood such as Fischbrötchen (fish sandwiches), salads, and canned seafood. The company formerly supplied its own seafood but has since sold the fishery. ', photo: '../../assets/restaurants/nordsee.jpg' }, { id: 6, name: 'Casavino', desc: 'The concept of CASAVINO is to be close to the customer, but also to trade at wholesale prices. In stores in the chain you get a discount when buying a "wine box" equal to 6 (or more) the same or different bottles of wine and / or spirits of your choice. So every bottle can be bought as part of a mixed carton at a better price.', photo: '../../assets/restaurants/casavino.jpg' } ]; @observable selectedLocation = {}; @action setSelectedLocation(location) { this.selectedLocation = location; } // Reserve your table // SelectLocation @observable reservedRestaurant = {}; @computed get getReservedRestaurant() { return this.reservedRestaurant; } @action setReservedRestaurant(location) { this.reservedRestaurant = location; } // SelectDate @observable selectedDate = undefined; @computed get getSelectedDate() { return this.selectedDate; } @action setSelectedDate(date) { this.selectedDate = date; } // SelectTime @observable selectedTime = { hour: '', minute: '' }; @computed get getSelectedTime() { return this.selectedTime; } @action setSelectedTime(time) { this.selectedTime = time; } // SelectPeople @observable selectedPeople = ''; @computed get getSelectedPeople() { return this.selectedPeople; } @action setSelectedPeople(num) { this.selectedPeople = num; } // CompleteReservation and ConfirmationModal @action resetReservation() { this.setReservedRestaurant({}); this.setSelectedDate(); this.setSelectedTime({}); this.setSelectedPeople(''); } @observable showModal = false; @computed get getModalState() { return this.showModal; } @action toggleModal() { this.showModal = !this.showModal; } } const restaurantsPropType = PropTypes.shape({ locations: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, desc: PropTypes.string, photo: PropTypes.string }) ), selectedLocation: PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, desc: PropTypes.string, photo: PropTypes.string }), setSelectedLocation: PropTypes.func, getLocations: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, desc: PropTypes.string, photo: PropTypes.string }) ), reservedRestaurant: PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, desc: PropTypes.string, photo: PropTypes.string }), setReservedRestaurant: PropTypes.func, getReservedRestaurant: PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, desc: PropTypes.string, photo: PropTypes.string }), selectedDate: PropTypes.object, getSelectedDate: PropTypes.object, setSelectedDate: PropTypes.func, selectedPeople: PropTypes.string, getSelectedPeople: PropTypes.string, setSelectedPeople: PropTypes.func, selectedTime: PropTypes.shape({ hour: PropTypes.string, minute: PropTypes.string }), getSelectedTime: PropTypes.shape({ hour: PropTypes.string, minute: PropTypes.string }), setSelectedTime: PropTypes.func, resetReservation: PropTypes.func, showModal: PropTypes.bool, getModalState: PropTypes.bool, toggleModal: PropTypes.func }); const restaurantsPropTypeDefaults = { locations: [], selectedLocation: {}, getLocations: [], setSelectedLocation: () => true, reservedRestaurant: {}, setReservedRestaurant: () => true, getReservedRestaurant: {}, selectedDate: {}, getSelectedDate: {}, setSelectedDate: () => true, selectedTime: {}, getSelectedTime: {}, setSelectedTime: () => true, selectedPeople: '', getSelectedPeople: '', setSelectedPeople: () => true, resetReservation: () => true }; export { Restaurants, restaurantsPropType, restaurantsPropTypeDefaults };
# Advanced C++ Projects This repository contains a collection of advanced C++ projects developed as part of the SEP200 course. Each project focuses on different aspects of C++ programming, including operator overloading, deep and shallow copying, class inheritance, polymorphism, templates, and multiple inheritance. These projects collectively showcase the application of advanced C++ concepts in solving complex problems. --- ## Projects Overview ### 1. Bank Manager Operator Overloading (`BankManagerOperatorOverloading`) This project demonstrates the use of operator overloading to manage investment accounts within a banking application. It includes the implementation of `==`, `+=`, and `-=` operators for account management. ### 2. Real Estate Management (`RealEstateManagement`) A simulation of a real estate management system where deep and shallow copies, operator overloading, and friendship are explored to manage house objects effectively. ### 3. Amazon Purchase Simulator (`AmazonPurchaseSimulator`) A program that simulates purchases from Amazon, showcasing the use of base and derived classes to handle different item types including books, DVDs, and digital music downloads. ### 4. Network Packet Parser (`NetworkPacketParser`) This project involves parsing network packets using polymorphism and virtual functions, distinguishing between UDP and TCP packet formats. ### 5. Company Database Template (`CompanyDatabaseTemplate`) An implementation of a company database using templates for parametric polymorphism, managing databases for regular employees and executives. ### 6. Sports Association Aggregator (`SportsAssociationAggregator`) A demonstration of aggregation and enumerations to manage sports teams within a sports association, highlighting the use of overriding operators. ### 7. Cellphone Customer Database (`CellphoneCustomerDatabase`) This project utilizes class variables, enumerations, and standard maps to manage a cellphone customer database efficiently. ### 8. Array Reorder Utility (`ArrayReorderUtility`) A utility that reorders arrays using a custom stack and queue classes, alongside standard STL algorithms. ### 9. Car Ratings STL Algorithms (`CarRatingsSTLAlgorithms`) An application of STL algorithms to process and analyze car ratings based on various metrics like reliability, fuel efficiency, and horse power. ### 10. Amphibious Vehicle Design (`AmphibiousVehicleDesign`) A complex project that uses multiple inheritance to design an amphibious vehicle class, inheriting properties from both an automobile and a boat class. --- ## Technologies Used - C++ - Object-Oriented Programming - Standard Template Library (STL) - Exception Handling - Smart Pointers ## Installation and Usage Each project directory contains source files and a Makefile. To compile a project, navigate to its directory and run the `make` command. Execute the compiled binary to run the program. ## Contributing Contributions to this repository are welcome. Please fork the repository and submit a pull request with your changes. --- For more detailed information on each project, refer to the individual project directories within this repository.
#pragma once #include "CommonOp.cuh" #include "CudaData.cuh" #include "DeviceManager.cuh" #include "VectorOp.cuh" #include <iostream> template <NumericType T> class Vector : public CudaData<T> { public: Vector(size_t len, cudaStream_t stream = 0); Vector(const T* hmem, size_t len, cudaStream_t stream = 0); Vector(const std::vector<T>& hmem, size_t len, cudaStream_t stream = 0); Vector(const Vector& other); Vector(const Matrix<T>& other); Vector(Vector&& other); Vector(Matrix<T>&& other); Vector& operator=(const Vector& other); Vector& operator=(Vector&& other); inline size_t Nlen() const { return this->m_len; } virtual std::vector<T> ToCPU() const override { return CudaData<T>::ToCPU(); } virtual inline std::vector<size_t> Shape() const override { return { Nlen() }; } public: using value_type = T; using int_type = Vector<int>; public: Matrix<T> Into(size_t ncol) const; public: T Sum() const; T Mean() const; ValueIndex<T> Max() const; ValueIndex<T> Min() const; Vector<T> Reversed() const; void Sort_(bool ascending = true); Vector<T> Sorted(bool ascending = true); private: size_t m_len; }; template <NumericType T> inline Vector<T>::Vector(size_t len, cudaStream_t stream) : m_len(len), CudaData<T>(sizeof(T) * len, stream) { } template <NumericType T> inline Vector<T>::Vector(const T* hmem, size_t len, cudaStream_t stream) : m_len(len), CudaData<T>(hmem, sizeof(T) * len, stream) { } template <NumericType T> inline Vector<T>::Vector(const std::vector<T>& hmem, size_t len, cudaStream_t stream) : m_len(len), CudaData<T>(hmem.data(), sizeof(T) * len, stream) { if (len != hmem.size()) { fprintf(stdout, "Size of vector [%lu] != len [%lu]" ". Unexpected behaviour may occur!\n", hmem.size(), len); } } template <NumericType T> inline Vector<T>::Vector(const Vector& other) : CudaData<T>(other), m_len(other.m_len) { #ifdef DEBUG_CONSTRUCTOR fprintf(stdout, "Vector copy ctor\n"); #endif } template <NumericType T> inline Vector<T>::Vector(const Matrix<T>& other) : CudaData<T>(other), m_len(other.Nrow() * other.Ncol()) { #ifdef DEBUG_CONSTRUCTOR fprintf(stdout, "Vector copy Matrix ctor\n"); #endif } template <NumericType T> inline Vector<T>::Vector(Vector&& other) : CudaData<T>(std::move(other)), m_len(other.m_len) { #ifdef DEBUG_CONSTRUCTOR fprintf(stdout, "Vector move ctor\n"); #endif } template <NumericType T> inline Vector<T>::Vector(Matrix<T>&& other) : CudaData<T>(std::move(other)), m_len(other.Nrow() * other.Ncol()) { #ifdef DEBUG_CONSTRUCTOR fprintf(stdout, "Vector move Matrix ctor\n"); #endif } template <NumericType T> inline Vector<T>& Vector<T>::operator=(const Vector& other) { #ifdef DEBUG_CONSTRUCTOR fprintf(stdout, "Vector copy assignment\n"); #endif CudaData<T>::operator=(other); this->m_len = other.m_len; return *this; } template <NumericType T> inline Vector<T>& Vector<T>::operator=(Vector&& other) { #ifdef DEBUG_CONSTRUCTOR fprintf(stdout, "Vector move assignment\n"); #endif CudaData<T>::operator=(std::move(other)); this->m_len = other.m_len; return *this; } template <NumericType T> inline Matrix<T> Vector<T>::Into(size_t ncol) const { return Matrix<T>(*this, ncol); } template <NumericType T> inline T Vector<T>::Sum() const { constexpr unsigned nt = NT; unsigned nb = (Nlen() + 2 * nt - 1) / (2 * nt); Vector<T> z(nb, this->S()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); #endif CommonOp::sum_unroll<T, nt> <<<nb, nt, 0, this->S()>>>(z.Data(), this->Data(), Nlen()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); Timer::Instance().ShowElapsedTime("Vector Sum"); #endif auto sum_blocks = z.ToCPU(); CUDA_CHECK_LAST(); StreamSync(this->S()); return std::accumulate(sum_blocks.begin(), sum_blocks.end(), (T) 0); } template <NumericType T> inline T Vector<T>::Mean() const { return Sum() / (T) Nlen(); } template <NumericType T> inline ValueIndex<T> Vector<T>::Max() const { constexpr unsigned nt = NT; unsigned nb = (Nlen() + 2 * nt - 1) / (2 * nt); Vector<ValueIndex<T>> z(nb, this->S()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); #endif CommonOp::max_unroll<T, nt> <<<nb, nt, 0, this->S()>>>(z.Data(), this->Data(), Nlen()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); Timer::Instance().ShowElapsedTime("Vector Max"); #endif auto max_blocks = z.ToCPU(); CUDA_CHECK_LAST(); StreamSync(this->S()); auto max_iter = std::max_element( max_blocks.begin(), max_blocks.end(), [](const auto& lhs, const auto& rhs) { return lhs.val < rhs.val; }); return *max_iter; } template <NumericType T> inline ValueIndex<T> Vector<T>::Min() const { constexpr unsigned nt = NT; unsigned nb = (Nlen() + 2 * nt - 1) / (2 * nt); Vector<ValueIndex<T>> z(nb, this->S()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); #endif CommonOp::min_unroll<T, nt> <<<nb, nt, 0, this->S()>>>(z.Data(), this->Data(), Nlen()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); Timer::Instance().ShowElapsedTime("Vector Min"); #endif auto min_blocks = z.ToCPU(); CUDA_CHECK_LAST(); StreamSync(this->S()); auto min_iter = std::min_element( min_blocks.begin(), min_blocks.end(), [](const auto& lhs, const auto& rhs) { return lhs.val < rhs.val; }); return *min_iter; } template <NumericType T> inline Vector<T> Vector<T>::Reversed() const { constexpr unsigned nt = NT; constexpr unsigned tile_dim = 512; unsigned nb = (Nlen() + tile_dim - 1) / tile_dim; Vector<T> z(Nlen(), this->S()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); #endif VectorOp::reversed<T, tile_dim, nt> <<<nb, nt, 0, this->S()>>>(z.Data(), this->Data(), Nlen()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); Timer::Instance().ShowElapsedTime("Vector Reversed"); #endif CUDA_CHECK_LAST(); StreamSync(this->S()); return z; } template <NumericType T> inline void Vector<T>::Sort_(bool ascending) { T padding_value { 0 }; auto n_next_po2 = VectorOp::next_po2(Nlen()); constexpr unsigned nt = NT; unsigned nb = (n_next_po2 + nt - 1) / nt; #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); #endif if (n_next_po2 == Nlen()) { for (unsigned k = 2; k <= n_next_po2; k <<= 1) { for (unsigned j = k >> 1; j > 0; j >>= 1) { VectorOp::sort<T><<<nb, nt, 0, this->S()>>>(this->Data(), k, j, Nlen(), ascending); } } } else { padding_value = ascending ? Max().val : Min().val; unsigned len = n_next_po2 - Nlen(); std::vector<T> padding_vec(len, padding_value); Vector<T> padding(padding_vec, len, this->S()); for (unsigned k = 2; k <= n_next_po2; k <<= 1) { for (unsigned j = k >> 1; j > 0; j >>= 1) { VectorOp::sort_padding<T><<<nb, nt, 0, this->S()>>>( this->Data(), padding.Data(), k, j, Nlen(), ascending); } } } #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(this->S()); Timer::Instance().ShowElapsedTime("Vector Sort"); #endif CUDA_CHECK_LAST(); StreamSync(this->S()); } template <NumericType T> inline Vector<T> Vector<T>::Sorted(bool ascending) { Vector<T> new_vec(*this); new_vec.Sort_(ascending); return new_vec; } template <NumericType T> inline Vector<T> Linear(T a, const Vector<T>& x, T b, const Vector<T>& y, T c) { cudaStream_t s = x.S(); auto len = std::min(x.Nlen(), y.Nlen()); if (x.S() != y.S()) { CUDA_CHECK(cudaDeviceSynchronize()); s = 0; } Vector<T> z(len, s); if (!HasSameShape(x, y)) { return z; } unsigned nb = DeviceManager::Curr().Prop().multiProcessorCount * MULT; unsigned nt = NT; #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); #endif CommonOp::axpbyc<<<nb, nt, 0, s>>>(z.Data(), a, x.Data(), b, y.Data(), c, len); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); Timer::Instance().ShowElapsedTime("Vector Linear"); #endif CUDA_CHECK_LAST(); StreamSync(s); return z; } template <NumericType T> inline Vector<T> Power(T c, const Vector<T>& x, T a, const Vector<T>& y, T b) { cudaStream_t s = x.S(); auto len = std::min(x.Nlen(), y.Nlen()); if (x.S() != y.S()) { CUDA_CHECK(cudaDeviceSynchronize()); s = 0; } Vector<T> z(len, s); if (!HasSameShape(x, y)) { return z; } unsigned nb = DeviceManager::Curr().Prop().multiProcessorCount * MULT; unsigned nt = NT; #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); #endif CommonOp::cxamyb<<<nb, nt, 0, s>>>(z.Data(), c, x.Data(), a, y.Data(), b, len); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); Timer::Instance().ShowElapsedTime("Vector Power"); #endif CUDA_CHECK_LAST(); StreamSync(s); return z; } template <NumericType T1, NumericType T2> inline Vector<T1> Binary(const Vector<T2>& x, const Vector<T2>& y, BinaryOp op) { cudaStream_t s = x.S(); auto len = std::min(x.Nlen(), y.Nlen()); if (x.S() != y.S()) { CUDA_CHECK(cudaDeviceSynchronize()); s = 0; } Vector<T1> z(len, s); if (!HasSameShape(x, y)) { return z; } unsigned nb = DeviceManager::Curr().Prop().multiProcessorCount * MULT; unsigned nt = NT; #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); #endif CommonOp::binary<T1, T2> <<<nb, nt, 0, s>>>(z.Data(), x.Data(), y.Data(), op, len); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); Timer::Instance().ShowElapsedTime("Vector Binary"); #endif CUDA_CHECK_LAST(); StreamSync(s); return z; } template <NumericType T1, NumericType T2> inline Vector<T1> Binary(const Vector<T2>& x, T2 y, BinaryOp op) { cudaStream_t s = x.S(); Vector<T1> z(x.Nlen(), s); unsigned nb = DeviceManager::Curr().Prop().multiProcessorCount * MULT; unsigned nt = NT; #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); #endif CommonOp::binary<T1, T2> <<<nb, nt, 0, s>>>(z.Data(), x.Data(), y, op, x.Nlen()); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); Timer::Instance().ShowElapsedTime("Vector Power"); #endif CUDA_CHECK_LAST(); StreamSync(s); return z; } template <NumericType T> inline T Inner(const Vector<T>& x, const Vector<T>& y) { cudaStream_t s = x.S(); auto len = std::min(x.Nlen(), y.Nlen()); if (x.S() != y.S()) { CUDA_CHECK(cudaDeviceSynchronize()); s = 0; } if (!HasSameShape(x, y)) { return 0; } constexpr unsigned nt = NT; unsigned nb = (len + 2 * nt - 1) / (2 * nt); Vector<T> z(nb, s); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); #endif VectorOp::inner_unroll<T, nt> <<<nb, nt, 0, s>>>(z.Data(), x.Data(), y.Data(), len); #ifdef DEBUG_PERFORMANCE Timer::Instance().Tick(s); Timer::Instance().ShowElapsedTime("Vector Inner Product"); #endif auto inner_blocks = z.ToCPU(); CUDA_CHECK_LAST(); StreamSync(s); return std::accumulate(inner_blocks.begin(), inner_blocks.end(), (T) 0); } template <NumericType T> inline T Mod2(const Vector<T>& x) { return Inner(x, x); } template <NumericType T> inline T Mod(const Vector<T>& x) { return std::sqrt(Mod2(x)); } template <NumericType T> inline T Distance(const Vector<T>& x, const Vector<T>& y) { if (&x == &y) return (T) 0; Vector<T> diff = x - y; return Mod(diff); }
import React from "react"; import "./App.css"; import "h8k-components"; import Articles from "./components/Articles"; const title = "Sorting Articles"; function App({ articles }) { const [articlesList, setArticlesList] = React.useState(articles); const [sortBy, setSortBy] = React.useState("upvotes"); React.useEffect(() => { sortArticles(); }, [sortBy]); const sortArticles = () => { console.log("sortArticles by: ", sortBy); let sortedArticles = [...articlesList]; if (sortBy === "upvotes") { sortedArticles.sort((a, b) => b.upvotes - a.upvotes); } else if (sortBy === "date") { sortedArticles.sort((a, b) => new Date(b.date) - new Date(a.date)); } setArticlesList(sortedArticles); }; return ( <div className="App"> <h8k-navbar header={title}></h8k-navbar> <div className="layout-row align-items-center justify-content-center my-20 navigation"> <label className="form-hint mb-0 text-uppercase font-weight-light"> Sort By </label> <button data-testid="most-upvoted-link" className="small" onClick={() => setSortBy("upvotes")} > Most Upvoted </button> <button data-testid="most-recent-link" className="small" onClick={() => setSortBy("date")} > Most Recent </button> </div> <Articles articles={articlesList} /> </div> ); } export default App;
import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, UPDATE_USER_INFO, USER_LOGOUT, USER_LIST_REQUEST, USER_LIST_SUCCESS, USER_LIST_FAIL, USER_LIST_RESET, USER_REGISTER_REQUEST, USER_REGISTER_SUCCESS, USER_REGISTER_FAIL, USER_DETAILS_REQUEST, USER_DETAILS_SUCCESS, USER_DETAILS_FAIL, USER_UPDATE_PROFILE_REQUEST, USER_UPDATE_PROFILE_SUCCESS, USER_UPDATE_PROFILE_FAIL, USER_UPDATE_PROFILE_RESET, USER_STATS_REQUEST, USER_STATS_SUCCESS, USER_STATS_FAIL, USER_STATS_RESET, USER_UPDATE_REQUEST, USER_UPDATE_SUCCESS, USER_UPDATE_FAIL, USER_UPDATE_RESET, USER_DELETE_REQUEST, USER_DELETE_SUCCESS, USER_DELETE_FAIL, ADD_LANGUAGE_TO_USER_REQUEST, ADD_LANGUAGE_TO_USER_SUCCESS, ADD_LANGUAGE_TO_USER_FAIL, } from '../constants/userConstants'; // USER LOGIN REDUCER export const userLoginReducer = (state = {}, action) => { switch(action.type) { case USER_LOGIN_REQUEST: return { loading: true } case USER_LOGIN_SUCCESS: return { loading: false, userInfo: action.payload } case UPDATE_USER_INFO: return { loading: false, userInfo: action.payload } case USER_LOGIN_FAIL: return { loading: false, error: action.payload } case USER_LOGOUT: return {} default: return state } } // USER REGISTER REDUCER export const userRegisterReducer = (state = {}, action) => { switch(action.type) { case USER_REGISTER_REQUEST: return { loading: true } case USER_REGISTER_SUCCESS: return { loading: false, userInfo: action.payload } case USER_REGISTER_FAIL: return {} default: return state } } // SET USER PROFILE export const userDetailsReducer = (state = { user: {} }, action) => { switch(action.type){ case USER_DETAILS_REQUEST: return { ...state, loading: true } case USER_DETAILS_SUCCESS: return { loading: false, user: action.payload } case USER_DETAILS_FAIL: return { loading: false, error: action.payload } default: return state } } export const userUpdateProfileReducer = (state = {}, action) => { switch(action.type) { case USER_UPDATE_PROFILE_REQUEST: return { loading: true } case USER_UPDATE_PROFILE_SUCCESS: return { loading: false, success: true, userInfo: action.payload } case USER_UPDATE_PROFILE_FAIL: return { loading: false, error: action.payload } case USER_UPDATE_PROFILE_RESET: return {} default: return state } } // NOTE: STATS NEEDS TO BE AN ARRAY BECAUSE WE ARE USING MAP + REDUCE ON IT!! NOT SURE HOW IT WORKED EARLIER. export const userStatsReducer = (state = { stats: [] }, action) => { console.log('stast redcuer'); switch(action.type) { case USER_STATS_REQUEST: return { ...state, loading: true} case USER_STATS_SUCCESS: return { ...state, loading: false, stats: action.payload } case USER_STATS_FAIL: return { ...state, loading: false, error: action.payload } case USER_STATS_RESET: return {} default: return state } } export const userListReducer = (state = { users: [] }, action) => { switch(action.type) { case USER_LIST_REQUEST: return { loading: true } case USER_LIST_SUCCESS: return { loading: false, users: action.payload } // console.log('users in reducer ', users); case USER_LIST_FAIL: return { loading: false, error: action.payload } default: return state; } } export const userUpdateReducer = (state = { user: {} }, action) => { switch(action.type) { case USER_UPDATE_REQUEST: return { loading: true } case USER_UPDATE_SUCCESS: return { loading: false, success: true } case USER_UPDATE_FAIL: return { loading: false, error: action.payload } case USER_UPDATE_RESET: return { user: {} } default: return state } } export const addLanguageToUserReducer = (state = { user: { languages: [] } }, action) => { switch(action.type) { case ADD_LANGUAGE_TO_USER_REQUEST: return { loading: true } case ADD_LANGUAGE_TO_USER_SUCCESS: return { loading: false, success: true, ...state, // user: [...state.user, action.payload] languages: action.payload } case ADD_LANGUAGE_TO_USER_FAIL: return { loading: false, success: false, error: action.payload } default: return state } } export const userDeleteReducer = (state = {}, action) => { switch(action.type) { case USER_DELETE_REQUEST: return { loading: true} case USER_DELETE_SUCCESS: return { loading: false, success: true } case USER_DELETE_FAIL: return { loading: false, error: action.payload } default: return state } }
import { filterActions } from "../constants"; const { SORT_LOW_TO_HIGH, SORT_HIGH_TO_LOW, FILTER_CATEGORY, FILTER_SIZES, FILTER_IDEAL_FOR, CLEAR_ALL } = filterActions; const Filter = ({filteredProductsState, filterDispatch}) => { return( <aside className="filters sticky right-0 top-16 z-10 p-2 h-96"> <header className="flex justify-between"> <h2 className="text-xl font-semibold">Filters</h2> <button className="text-xs text-blue-500" onClick={()=>filterDispatch({type: CLEAR_ALL})}> CLEAR ALL </button> </header> <div className="text-center px-4 mt-2 flex flex-col gap-2"> <div className="flex flex-col gap-2"> <h3 className="text-lg">Sort by</h3> <label className="cursor-pointer flex gap-2 items-center"> <input type="radio" name="sort-by-price" checked={filteredProductsState.sortBy === "high-to-low"} onChange={() => filterDispatch({ type: SORT_HIGH_TO_LOW })} /> High-to-Low </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="radio" name="sort-by-price" checked={filteredProductsState.sortBy === "low-to-high"} onChange={() => filterDispatch({ type: SORT_LOW_TO_HIGH })} /> Low-to-High </label> </div> <div className="flex flex-col gap-2"> <h3 className="text-lg">Sizes</h3> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" checked={filteredProductsState.sizes.includes("s")} onChange={() => filterDispatch({ type: FILTER_SIZES, payload: "s" })} /> S </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" checked={filteredProductsState.sizes.includes("m")} onChange={() => filterDispatch({ type: FILTER_SIZES, payload: "m" })} /> M </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" checked={filteredProductsState.sizes.includes("l")} onChange={() => filterDispatch({ type: FILTER_SIZES, payload: "l" })} /> L </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" checked={filteredProductsState.sizes.includes("xl")} onChange={() => filterDispatch({ type: FILTER_SIZES, payload: "xl" })} /> XL </label> </div> <div className="flex flex-col gap-2"> <h3 className="text-lg">Brands</h3> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" onChange={() => filterDispatch({ type: FILTER_CATEGORY, payload: "FTX" })} checked={filteredProductsState.categories.includes("FTX")} /> FTX </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" onChange={() => filterDispatch({ type: FILTER_CATEGORY, payload: "Allen Solly" })} checked={filteredProductsState.categories.includes("Allen Solly")} /> ALLEN SOLLY </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" onChange={() => filterDispatch({ type: FILTER_CATEGORY, payload: "LEVI'S" })} checked={filteredProductsState.categories.includes("LEVI'S")} /> LEVI'S </label> </div> <div className="flex flex-col gap-2"> <h3 className="text-lg">Ideal For</h3> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" onChange={() => filterDispatch({ type: FILTER_IDEAL_FOR, payload: "Men" })} checked={filteredProductsState.idealFor.includes("Men")} /> Men </label> <label className="cursor-pointer flex gap-2 items-center"> <input type="checkbox" onChange={() => filterDispatch({ type: FILTER_IDEAL_FOR, payload: "Women" })} checked={filteredProductsState.idealFor.includes("Women")} /> Women </label> </div> </div> </aside> ); } export { Filter };
## --- Day 5: How About a Nice Game of Chess? --- You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching [hacking](https://en.wikipedia.org/wiki/Hackers_(film)) [movies](https://en.wikipedia.org/wiki/WarGames). The _eight-character password_ for the door is generated one character at a time by finding the [MD5](https://en.wikipedia.org/wiki/MD5) hash of some Door ID (your puzzle input) and an increasing integer index (starting with `` 0 ``). A hash indicates the _next character_ in the password if its [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) representation starts with _five zeroes_. If it does, the sixth character in the hash is the next character of the password. For example, if the Door ID is `` abc ``: * The first index which produces a hash that starts with five zeroes is `` 3231929 ``, which we find by hashing `` abc3231929 ``; the sixth character of the hash, and thus the first character of the password, is `` 1 ``. * `` 5017308 `` produces the next interesting hash, which starts with `` 000008f82... ``, so the second character of the password is `` 8 ``. * The third time a hash starts with five zeroes is for `` abc5278568 ``, discovering the character `` f ``. In this example, after continuing this search a total of eight times, the password is `` 18f47a30 ``. Given the actual Door ID, _what is the password_? ## --- Part Two --- As the door slides open, you are presented with a second door that uses a slightly more <span title="This one says 'WOPR' in block letters.">inspired</span> security mechanism. Clearly unimpressed by the last version (in what movie is the password decrypted _in order_?!), the Easter Bunny engineers have worked out [a better solution](https://www.youtube.com/watch?v=NHWjlCaIrQo&amp;t=25). Instead of simply filling in the password from left to right, the hash now also indicates the _position_ within the password to fill. You still look for hashes that begin with five zeroes; however, now, the _sixth_ character represents the _position_ (`` 0 ``-`` 7 ``), and the _seventh_ character is the character to put in that position. A hash result of `` 000001f `` means that `` f `` is the _second_ character in the password. Use only the _first result_ for each position, and ignore invalid positions. For example, if the Door ID is `` abc ``: * The first interesting hash is from `` abc3231929 ``, which produces `` 0000015... ``; so, `` 5 `` goes in position `` 1 ``: `` _5______ ``. * In the previous method, `` 5017308 `` produced an interesting hash; however, it is ignored, because it specifies an invalid position (`` 8 ``). * The second interesting hash is at index `` 5357525 ``, which produces `` 000004e... ``; so, `` e `` goes in position `` 4 ``: `` _5__e___ ``. You almost choke on your popcorn as the final character falls into place, producing the password `` 05ace8e3 ``. Given the actual Door ID and this new method, _what is the password_? Be extra proud of your solution if it uses a cinematic "decrypting" animation.
window.utils = { loadViews: function(views, callback) { var self = this; var count = views.length; var current = 0; var deferreds = []; $.each(views, function(index, view) { if (window[view.name]) { deferreds.push($.get('views/' + view.name + '.html', function(data) { // Load the template window[view.name].prototype.template = data; // Create a global reference to the view window[view.reference] = new window[view.name](); // Set the view's properties $.extend(window[view.reference], view); // Update the progress bar var progress = (++current) / count * 100; self.updateLoading(progress); }, 'html')); } else { console.error(view.name + " wasn't loaded. Did you include the js file?"); } }); $.when.apply(null, deferreds).done(callback); }, refreshSession: function(callback) { session.clear(); session.fetch({ success: function(session) { if(callback) { callback(session); } } }); }, createRouter: function(views) { // Create a Backbone Router var Router = Backbone.Router.extend({ initialize: function(views) { // Render all autoload views $.each(views, function(index, view) { if(view.autoLoad) { utils.renderView(view); } }); } }); var router = new Router(views); // Create routes for views $.each(views, function(index, view) { if(view.route !== undefined) { router.route(view.route, "", function() { utils.renderView(view, arguments); }); } }); return router; }, renderView: function(view, args) { utils.checkAuth(view.accessLevel, function() { if(window[view.reference]) { window[view.reference].render(args); } else { console.error("Cannot render " + view.reference); } }); }, checkAuth: function(requiredAccessLevel, callback) { var sessionAccessLevel = session.get("accessLevel") || 0; if(requiredAccessLevel > sessionAccessLevel) { router.navigate("/", true); } else { callback(); } }, formToJSON: function(form, callback) { var obj = {}; $(form).find("[name]").each(function(i, el) { obj[$(el).attr("name")] = $(el).val(); }); callback(obj); }, updateLoading: function(progress) { $('#loading .bar').width(progress + "%"); }, hideLoading: function() { $('#loading').hide(); } };
# ECON3382 Computational Investing ###### Members: Barry Qie, Dehao Yuan, Sherry Lin (Alphabetical Order) ## Stationary Portfolio Construction * [Step 1: Get the stock price.](#1) * [Step 2: Compute stationary matrix.](#2) * [Step 3: Compute optimal portfolio.](#3) * [Step 4: Output the weights.](#4) * [Step 5: Get the portfolio price.](#5) * [Step 6: Stationary Test in new periods](#6) ## README * Here is the [Project Proposal](https://drive.google.com/open?id=16V2bYNoaRRau_cfTC_LXMwtqL-aWmd_0). * To check the outline, simply check the [main function](#0) and its output. * To check the details, [here](#b) is the breakdown. from quantopian.research import run_pipeline from quantopian.pipeline import Pipeline from quantopian.research import prices, symbols from quantopian.pipeline.data import Fundamentals from quantopian.pipeline.data.sentdex import sentiment from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.filters import StaticAssets, StaticSids from quantopian.pipeline.filters.morningstar import Q500US from quantopian.pipeline.classifiers.morningstar import Sector import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from statsmodels.tsa.stattools import adfuller from scipy.interpolate import interp1d import matplotlib.pyplot as plt from datetime import datetime base_universe = Q500US() sector = Fundamentals.morningstar_sector_code.latest basic_materials = sector.element_of([101]) & base_universe cons_cyclical = sector.element_of([102]) & base_universe real_estate = sector.element_of([103]) & base_universe cons_defensive = sector.element_of([205]) & base_universe healthcare = sector.element_of([206]) & base_universe utilities = sector.element_of([207]) & base_universe comm_services = sector.element_of([308]) & base_universe energy = sector.element_of([309]) & base_universe industrials = sector.element_of([310]) & base_universe tech = sector.element_of([311]) & base_universe <a id='0'></a> ## MAIN FUNCTION ##############################https://research-i-0b40635fa06ebbe7f.prd.int.dynoquant.com/user/5cf38dfee27f6a003e5aec01/notebooks/ECON3382%20Project/Complete_main.ipynb#MAIN-FUNCTION ###### Hyper-parameters ###### ############################## train_start = '2005-01-01' train_end = '2011-01-01' field = 'close' sector = tech ############################## ###### Hyper-parameters ###### ############################## # Step 1: Get the stock price and the security identities. stockprice, sids = get_stock_price(sector, start_time=train_start, end_time=train_end, fields=field) print 'stockprice is a DataFrame with the shape: ', stockprice.shape print 'sids is a NumPy array with the shape: ', sids.shape # Step 2: Compute the "stationary matrix". stationary_matrix = get_stationary_matrix(stockprice, sids) print 'stationary_matrix is a symmetrical matrix with the shape: ', stationary_matrix.shape print 'take a glance on the stationary matrix: \n', stationary_matrix[0:5,0:5] # Step 3: Construct the portfolio according to the stationary matrix. tree_list = get_portfolio_tree(stockprice, sids, stationary_matrix, max_num_stocks=30) print 'tree_list is a list of binary tree, which stores the information of the portfolio.' print 'An instance of the binary tree is: ' tree_list[0].print_tree(0) # Step 4: Get the weights of each portfolios. weights = reconstruct_portfolio(tree_list) print 'The final output is a DataFrame which stores how many "weights" should be placed on each stock: ' print weights[0].tail() print ('') print_code(weights) trade_start = '2005-01-01' trade_end = '2018-01-01' for max_num_stocks in range(2,len(sids)): tree_list = get_portfolio_tree(stockprice, sids, stationary_matrix, max_num_stocks=max_num_stocks) weights = reconstruct_portfolio(tree_list) for i in range(len(weights)): plt.axvline(x=datetime(int(train_end[0:4]),1,1)) plt.plot(get_portfolio_price(weights[i], trade_start, trade_end, 'price', frequency = 'daily'), alpha=0.7, label='#stocks: '+str(len(weights[i]))) plt.xlabel('time') plt.ylabel('price') plt.title('max #stocks: '+str(max_num_stocks)) plt.legend() plt.show() ################################################################################################ ################################################################################################ <a id='I'></a> # Stationary Portfolio Construction <a id='1'></a> ### Step 1: Given the sector, staring time and ending time, return the stock price. # USEquityPricing: open, high, low, close def get_stock_price(sector, start_time, end_time, fields='close'): #frequency: daily if fields == 'open': pipe = Pipeline(columns={'price' : USEquityPricing.open.latest},screen=sector) elif fields == 'high': pipe = Pipeline(columns={'price' : USEquityPricing.high.latest},screen=sector) elif fields == 'low': pipe = Pipeline(columns={'price' : USEquityPricing.low.latest},screen=sector) else: pipe = Pipeline(columns={'price' : USEquityPricing.close.latest},screen=sector) results = run_pipeline(pipe, start_time, end_time) unstacked_results = results.unstack() unstacked_results = unstacked_results.dropna(axis=1, how='any') sids = unstacked_results.columns returned_sids = np.zeros(len(sids), dtype='u4') for i in range(len(sids)): returned_sids[i] = sids[i][1].sid unstacked_results.columns = returned_sids return unstacked_results, returned_sids ################################################################################################ ################################################################################################ <a id='2'></a> ### Step 2: Get the stationary matrix. The stationary matrix is defined to be: $A^0=\left[a_{ij}\right]$, where $a_{ij}=ADF(s_i-\beta_{ij}s_j)$, and $\beta_{ij}$ is the regression slope and $a_{ii}=ADF(s_i)$. * Notice that $a_{ij}$ measures the stationarility of the pair trading of $s_i$ and $s_j$. $a_{ii}$ measures the stationarility of an individual stock. def get_stationary_matrix(price, sids): stationary_matrix = np.zeros([len(sids), len(sids)]) n = len(sids) for i in range(0,n-1): for j in range(i,n): beta = LinearRegression().fit(price.values[:,i].reshape(-1,1), price.values[:,j].reshape(-1,1)) beta = np.asscalar(beta.coef_) stationary_matrix[i,j] = adfuller(price.values[:,j]-beta*price.values[:,i])[1] for i in range(n): stationary_matrix[i,i] = adfuller(price.values[:,i])[1] stationary_matrix = stationary_matrix + stationary_matrix.T stationary_matrix[0:n,0:n] = stationary_matrix[0:n,0:n] / 2 return stationary_matrix ################################################################################################ ################################################################################################ <a id='3'></a> ### Step 3: Construct portfolios according to the stationary matrix. The detail of the algorithm is: * Find the entry $a_{mn}$ such that $a_{mn}<a_{mm}$ and $a_{mn}<a_{nn}$. Replace $s_m$ and $s_n$ with a combo of $s_m$ and $s_n$: $s_m-\beta_{mn}s_n$. Record $(m,n)$ and recompute the ADF matrix $A^1=\left[a_{ij}\right]$. * Recursively do that until there is no entry with $a_{ij}<a_{ii}$ and $a_{ij}<a_{jj}$ for all $a_{ij}\in A^k$, where $k \in \mathbb{N}$. def get_portfolio_tree(price, sids, stationary_matrix, verbose=False, max_num_stocks=10): price_copy = price.copy() stationary_matrix_copy = stationary_matrix.copy() tree = [] for sid in sids: tree.append(Portfolio(sid=sid)) while True: N = len(stationary_matrix_copy) # Find good pair trading. diag = stationary_matrix_copy[np.arange(N),np.arange(N)] cols = np.tile(diag, (N,1)) rows = cols.T stationary_matrix_copy[(stationary_matrix_copy>cols)&(stationary_matrix_copy>rows)] = np.nan col_diff = cols - stationary_matrix_copy row_diff = rows - stationary_matrix_copy multiply_diff = col_diff * row_diff if np.nanmax(multiply_diff) > 0: indices = np.where(multiply_diff==np.nanmax(multiply_diff)) combine_x = min(indices[0][0], indices[1][0]) combine_y = max(indices[0][0], indices[1][0]) if tree[combine_x].num_stocks > max_num_stocks or tree[combine_y].num_stocks > max_num_stocks: stationary_matrix_copy[combine_x][combine_y] = (diag[combine_x]+diag[combine_y]) / 2 stationary_matrix_copy[combine_y][combine_x] = (diag[combine_x]+diag[combine_y]) / 2 continue else: # If there is no good trading, end the loop. break # Manipulate the price. price_x = price_copy[price_copy.columns[combine_x]] price_y = price_copy[price_copy.columns[combine_y]] beta_xy = LinearRegression().fit(price_x.values.reshape(-1,1), price_y.values.reshape(-1,1)) beta_xy = np.asscalar(beta_xy.coef_) price_copy[price_copy.columns[combine_x]] = price_y.values - beta_xy * price_x.values price_copy = price_copy.drop(price_copy.columns[combine_y], axis=1) # Manipulate the stationary matrix. stationary_matrix_copy = np.delete(stationary_matrix_copy, combine_y, axis=0) stationary_matrix_copy = np.delete(stationary_matrix_copy, combine_y, axis=1) stationary_matrix_copy[combine_x,combine_x] = adfuller(price_copy[price_copy.columns[combine_x]])[1] for i in np.setdiff1d(np.arange(N-1), combine_x): price_y = price_copy[price_copy.columns[i]] beta = LinearRegression().fit(price_x.values.reshape(-1,1), price_y.values.reshape(-1,1)) beta = np.asscalar(beta.coef_) stationary_matrix_copy[combine_x,i] = adfuller(price_y.values - beta * price_x.values)[1] stationary_matrix_copy[i,combine_x] = stationary_matrix_copy[combine_x,i] # Manipulate the tree list. update_tree(tree, combine_x, combine_y, beta_xy) if verbose: print '>', if verbose: print '' print 'Final number of the trees: ', len(tree) return tree *The Portfolio object is a binary tree to store the portfolio information.* class Portfolio: """ It is a node storing information of a portfolio. """ def __init__(self, sid=None, left=None, right=None, beta=None, empty=False): if empty: # Empty node. self.sid = None self.left = None self.right = None self.beta = None self.num_stocks = 0 self.isempty = True else: if sid is not None: # If the node is a single stock, store the sid. self.sid = sid self.left = Portfolio(empty=True) self.right = Portfolio(empty=True) self.beta = None self.num_stocks = 1 self.isempty = False else: # If the node is a combo, store the left and the right nodes and the beta. self.sid = None self.left = left self.right = right self.beta = beta self.num_stocks = left.num_stocks + right.num_stocks self.isempty = False def print_tree(self, depth=0): """Print the tree with a rotation of 90 degrees.""" if self.isempty: return self.right.print_tree(depth+1) for i in range(depth): print '\t', if self.sid is not None: print self.sid else: print round(self.beta*100) / 100 self.left.print_tree(depth+1) def construct_portfolio(self, sids, weights, multiple=1): if self.sid is not None: sids.append(self.sid) weights.append(multiple) else: self.right.construct_portfolio(sids, weights, multiple*(-self.beta)) self.left.construct_portfolio(sids, weights, multiple) def update_tree(tree, combine_x, combine_y, beta): new_tree = Portfolio(left=tree[combine_y], right=tree[combine_x], beta=beta) tree[combine_x] = new_tree del tree[combine_y] ################################################################################################ ################################################################################################ <a id='4'></a> ### Step 4: Compute the weight of each stock from the Portfolio tree. def reconstruct_portfolio(tree_list): weights = [] for tree in tree_list: sid = [] weight = [] tree.construct_portfolio(sids=sid, weights=weight) output = pd.DataFrame(np.zeros([len(sid), 2]), columns=['sid', 'weight']) output['sid'] = np.array(sid) output['weight'] = np.array(weight) weights.append(output) return weights ################################################################################################ ################################################################################################ <a id='5'></a> ### Step 5: Get the portfolio price. Construct the price of the portfolio according to the weight. def get_portfolio_price(weight, start_time, end_time, pfield, frequency): """ pfield: 'price', 'open_price', 'high', 'low', 'close_price', 'volume' frequency: 'daily', 'minute' """ assets = weight['sid'] price = get_pricing(assets, start_time, end_time, fields=pfield) portfolio_price = np.dot(price, weight['weight']) return pd.Series(portfolio_price, index=price.index) ################################################################################################ ################################################################################################ <a id='6'></a> ### Step 6: Test the stationarity in new periods. The stationarity is given by the Hurst exponent. def get_overfitting_adf(portfoliop_series): adf = adfuller(portfoliop_series.values) return adf[1] ################################################################################################ ################################################################################################ ### Step 7: Transfer the weights to the IDE. def print_code(weights): for weight in weights: print ('sids = np.array(['), for i in range(len(weight)): print(str(weight['sid'][i])+','), print ('\b\b'), print ('])') print ('weights = np.array(['), for i in range(len(weight)): print(str(weight['weight'][i])+','), print ('\b\b'), print ('])') print ('')
import math import pyglet import colors import config_data import global_game_data import graph_data class Scoreboard: player_name_display = [] player_traveled_display = [] player_excess_distance_display = [] player_time_exausted_display = [] player_path_display = [] def __init__(self, batch, group): self.batch = batch self.group = group self.stat_height = 32 self.stat_width = 400 self.number_of_stats = 5 self.base_height_offset = 20 self.font_size = 16 self.distance_to_exit_label = pyglet.text.Label('Direct Distance To Exit : 0', x=0, y=0, font_name='Arial', font_size=self.font_size, batch=batch, group=group) self.winner_label = pyglet.text.Label('Winner : 0', x=10, y=10, font_name='Arial', font_size=self.font_size, batch=batch, group=group) self.distance_to_exit = 0 self.minimum_distance = None self.winner = 'None' for index, player in enumerate(config_data.player_data): player_name_label = pyglet.text.Label(str(index + 1) + " " + player[0], x=0, y=0, font_name='Arial', font_size=self.font_size, batch=batch, group=group, color=player[2][colors.TEXT_INDEX]) self.player_name_display.append((player_name_label, player)) traveled_distance_label = pyglet.text.Label("Distance Traveled:", x=0, y=0, font_name='Arial', font_size=self.font_size, batch=batch, group=group, color=player[2][colors.TEXT_INDEX]) self.player_traveled_display.append( (traveled_distance_label, player)) excess_distance_label = pyglet.text.Label("Excess Distance Traveled:", x=0, y=0, font_name='Arial', font_size=self.font_size, batch=batch, group=group, color=player[2][colors.TEXT_INDEX]) self.player_excess_distance_display.append( (excess_distance_label, player)) time_label = pyglet.text.Label("Time Exausted:", x=0, y=0, font_name='Arial', font_size=self.font_size, batch=batch, group=group, color=player[2][colors.TEXT_INDEX]) self.player_time_exausted_display.append( (time_label, player)) path_label = pyglet.text.Label("", x=0, y=0, font_name='Arial', font_size=self.font_size, batch=batch, group=group, color=player[2][colors.TEXT_INDEX]) self.player_path_display.append( (path_label, player)) def update_elements_locations(self): self.distance_to_exit_label.x = config_data.window_width - self.stat_width self.distance_to_exit_label.y = config_data.window_height - self.stat_height for index, (display_element, player) in enumerate(self.player_name_display): display_element.x = config_data.window_width - self.stat_width display_element.y = config_data.window_height - self.base_height_offset - self.stat_height * 2 - self.stat_height * (index * self.number_of_stats) for index, (display_element, player) in enumerate(self.player_traveled_display): display_element.x = config_data.window_width - self.stat_width display_element.y = config_data.window_height - self.base_height_offset - self.stat_height * 3 - self.stat_height * (index * self.number_of_stats) for index, (display_element, player) in enumerate(self.player_excess_distance_display): display_element.x = config_data.window_width - self.stat_width display_element.y = config_data.window_height - self.base_height_offset - self.stat_height * 4 - self.stat_height * (index * self.number_of_stats) for index, (display_element, player) in enumerate(self.player_path_display): display_element.x = config_data.window_width - self.stat_width display_element.y = config_data.window_height - self.base_height_offset - self.stat_height * 5 - self.stat_height * (index * self.number_of_stats) for index, (display_element, player) in enumerate(self.player_time_exausted_display): display_element.x = config_data.window_width - self.stat_width display_element.y = config_data.window_height - self.base_height_offset - self.stat_height * 6 - self.stat_height * (index * self.number_of_stats) self.winner_label.x = config_data.window_width - self.stat_width self.winner_label.y = config_data.window_height - self.base_height_offset - self.stat_height * 1 - self.stat_height * (0 * self.number_of_stats) def update_paths(self): for index in range(len(config_data.player_data)): self.player_path_display[index][0].text = self.wrap_text(str(global_game_data.graph_paths[index])) def update_distance_to_exit(self): start_x = graph_data.graph_data[global_game_data.current_graph_index][0][0][0] start_y = graph_data.graph_data[global_game_data.current_graph_index][0][0][1] end_x = graph_data.graph_data[global_game_data.current_graph_index][-1][0][0] end_y = graph_data.graph_data[global_game_data.current_graph_index][-1][0][1] self.distance_to_exit = math.sqrt(pow(start_x - end_x, 2) + pow(start_y - end_y, 2)) self.distance_to_exit_label.text = 'Direct Distance To Exit : ' + "{0:.0f}".format(self.distance_to_exit) def wrap_text(self, input): wrapped_text = (input[:44] + ', ...]') if len(input) > 44 else input return wrapped_text def update_distance_traveled(self): for display_element, player_configuration_info in self.player_traveled_display: for player_object in global_game_data.player_objects: if player_object.player_config_data == player_configuration_info: display_element.text = "Distance Traveled: " + str(int(player_object.distance_traveled)) for display_element, player_configuration_info in self.player_excess_distance_display: for player_object in global_game_data.player_objects: if player_object.player_config_data == player_configuration_info: display_element.text = "Excess Distance Traveled: " + str(max(0, int(player_object.distance_traveled-self.distance_to_exit))) def update_time(self): for display_element, player_configuration_info in self.player_time_exausted_display: for player_object in global_game_data.player_objects: if player_object.player_config_data == player_configuration_info: #player_object.time_exausted += 1 display_element.text = "Time Exausted:" + str(round(player_object.time_exausted * 0.01, 1)) def update_winner(self): minimum_distance = float('inf') for player_object in global_game_data.player_objects: if player_object.distance_traveled != 0: distance = int(player_object.distance_traveled) if distance < minimum_distance: if config_data.player_data.index(player_object.player_config_data) != global_game_data.current_player_index: if config_data.player_data.index(player_object.player_config_data) != 0 or player_object.testHitTarget: # Cannot be TEST unless hit target minimum_distance = distance self.winner = player_object.player_config_data[0] # Update the winner_label with the winner's name self.winner_label.text = f'Leader/Winner: {self.winner}' def update_scoreboard(self): self.update_elements_locations() self.update_paths() self.update_distance_to_exit() self.update_distance_traveled() self.update_time() self.update_winner()
<h1>Task Management Application</h1> A comprehensive task management solution built with Java, Spring Boot for the backend, and React for the frontend. This application is designed to streamline the process of task management, providing users with a robust platform to add, manage, and collaborate on tasks efficiently. With integrated security features, email verification, it's the perfect tool for anyone looking to enhance their productivity. <h2>Features</h2> - **User Authentication and Authorization**: Secure login and registration process with Spring Security, ensuring data protection and privacy. - **Email Verification**: Enhances security by verifying users' email addresses during the registration process. - **Task Management**: Users can easily add, update, and delete their tasks, organizing their daily activities effectively. - **Daily Task Assignments**: Allows users to assign tasks for specific days, aiding in better planning and time management. <h2>Technologies Used</h2> - **Backend**: Java, Spring Boot, Spring Security - **Frontend**: React - **Database**: PostGreSql, Amazon AWS S3 Bucket - **Other**: MailDev for mail verification <h2>Getting Started</h2> To get a local copy up and running follow these simple steps. <h3>Prerequisites</h3> - Install JDK (version 11 or above) - Install Node.js (version 14 or above) - Install PostGreSql and configure it accordingly. - Install MailDev https://github.com/jeandonaldroselin/maildev - Configure your Amazon AWS S3 Bucket <h3>Installation</h3> 1. Clone the repository ``` git clone https://github.com/Kashyl1/Task-Management-app.git ``` 2.Navigate to the backend directory and run the Spring Boot application ``` ./mvnw spring-boot:run ``` 3. Navigate to the frontend directory, install dependencies, and start the React application ``` cd ../frontend npm install npm start ``` The application should now be running on `localhost:8080` for the backend and `localhost:3000` for the frontend. 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request <h2>License</h2> Distributed under the MIT License. <h2> Login and Registration </h2> ![image](https://github.com/Kashyl1/Task-Management/assets/92478936/0319baa0-1b0d-403f-b195-86dc618a3580) ![image](https://github.com/Kashyl1/Task-Management/assets/92478936/d1c28cbd-4b17-4065-b804-d4b6ac88771d) ![image](https://github.com/Kashyl1/Task-Management/assets/92478936/b0e55d9c-42b9-4c34-a1d9-df6140c5be37)
(ns gurps.pages.character.items.melee-weapons-page (:require ["twrnc" :refer [style] :rename {style tw}] [re-frame.core :as rf] [gurps.utils.i18n :as i18n] [gurps.utils.helpers :refer [->int]] [gurps.widgets.underlined-input :refer [underlined-input]] [gurps.widgets.dropdown :refer [dropdown]] [gurps.widgets.base :refer [view text]] [gurps.pages.character.widgets.helpers :refer [generify-key]] [gurps.pages.character.utils.skills :refer [grouped-skills]] [gurps.utils.debounce :refer [debounce-and-dispatch debounce]] [taoensso.timbre :as log])) (defn- row [col1 col2 col3 col4 col5 col6] [:> view {:style (tw "flex flex-row h-6 gap-2")} [:> view {:style (tw "w-3/12")} col1] [:> view {:style (tw "w-2/12")} col2] [:> view {:style (tw "w-2/12")} col3] [:> view {:style (tw "w-2/12")} col4] [:> view {:style (tw "w-2/12")} col5] [:> view {:style (tw "w-1/12 pr-4")} col6]]) (defn- header [] [row [:> text {:style (tw "font-bold capitalize")} (i18n/label :t/weapon)] [:> text {:style (tw "font-bold text-center capitalize")} (i18n/label :t/dmg-thrust)] [:> text {:style (tw "font-bold text-center capitalize")} (i18n/label :t/dmg-swing)] [:> text {:style (tw "font-bold text-center capitalize")} (i18n/label :t/reach)] [:> text {:style (tw "font-bold text-center capitalize")} (i18n/label :t/parry)] [:> text {:style (tw "font-bold capitalize")} (i18n/label :t/weight)]]) ;; TODO: AI generated. has an off-by one error somewhere ;; +3 -> 1d ;; +4 -> 1d+1 ;; +5 -> 1d+2 ;; +6 -> 2d (defn dice-addition [dice-roll n] (let [roll-parts (re-find #"(\d+)d\+?(\d*)" dice-roll) roll-dices (js/parseInt (nth roll-parts 1)) roll-addition (js/parseInt (nth roll-parts 2 0)) abs-n (abs n)] (cond (neg? n) (let [dices (max 0 (- roll-dices (quot abs-n 3))) remaining-addition (max 0 (- roll-addition (rem abs-n 3)))] (str dices (when (pos? dices) "d") (when (pos? remaining-addition) (str "+" remaining-addition)))) (pos? n) (loop [dices roll-dices remaining n addition roll-addition] (cond (>= remaining 7) (recur (+ dices 2) (- remaining 7) addition) (>= remaining 4) (recur (+ dices 1) (- remaining 4) addition) :else (let [total-dices (+ dices (quot (+ remaining 2) 3)) remaining-addition (rem (+ remaining 2) 3)] (str total-dices "d" (when (pos? remaining-addition) (str "+" remaining-addition)))))) :else (str (when (pos? roll-dices) (str roll-dices "d")) (when (pos? roll-addition) (str "+" roll-addition)))))) (def empty-weapon {:name "" :weight 0 :thr-mod "1d" :swg-mod "1d" :reach "" :parry nil}) ;; NOTE (MELEE/2)+3; round down (defn lvl->parry [lvl] (let [parry (quot (+ lvl 2) 3)] (if (pos? parry) parry 0))) (defn melee-weapons-page [] [:> view {:style (tw "flex flex-col gap-2 bg-white flex-grow p-2")} [header] (let [weapons (some-> (rf/subscribe [:items/melee-weapons]) deref) thr (some-> (rf/subscribe [:attributes/damage-thrust]) deref) swg (some-> (rf/subscribe [:attributes/damage-swing]) deref) weapon-parries (some-> (rf/subscribe [:defenses/parries]) deref) parriable-weapons (some-> (rf/subscribe [:skills/parriable-weapons]) deref)] ;; (log/info "melee-weapons-page" weapon-parries) (map-indexed (fn [i {:keys [name thr-mod swg-mod weight reach parry]}] (let [thr-ref (atom nil) swg-ref (atom nil)] ^{:key (str "weapon-" i)} [row ;; name [underlined-input {:val name :on-change-text #(debounce-and-dispatch [:items.melee/update, i, :name, %] 500)}] ;; damage-thr [underlined-input {:val thr-mod ;; (dice-addition thr thr-mod) :on-change-text (debounce (fn [e] (rf/dispatch [:items.melee/update, i, :thr-mod, e]) ;; TODO: review this dice addition logic ;; (rf/dispatch [:items.melee/update, i, :thr-mod, (->int e)]) ;; (.clear ^js @thr-ref) ) 1000) :get-ref #(reset! thr-ref %) ;; :input-mode "numeric" ;; :max-length 3 :text-align "center" :clear-on-input? true}] ;; damage-swg [underlined-input {:val swg-mod ;; (dice-addition swg swg-mod) :on-change-text (debounce (fn [e] (rf/dispatch [:items.melee/update, i, :swg-mod, e]) ;; (rf/dispatch [:items.melee/update, i, :swg-mod, (->int e)]) ;; (.clear ^js swg-ref) ) 1000) :get-ref #(reset! swg-ref %) ;; :input-mode "numeric" ;; :max-length 3 :text-align "center" :clear-on-input? true}] ;; reach [underlined-input {:val reach :text-align "center" :on-change-text #(rf/dispatch [:items.melee/update, i, :reach, %])}] ;; parry [dropdown {:val parry :placeholder (when parry (str ((keyword parry) weapon-parries))) :list-style (tw "w-26 left-70") :placeholder-style (tw "text-center text-xs") :item-style (tw "capitalize") :selected-style (tw "capitalize text-center text-xs") :on-change #(rf/dispatch [:items.melee/update, i, :parry, %]) :data (->> parriable-weapons (map #(do {:label (:name %) :value (:k %)})))}] ;; weight [underlined-input {:val weight :input-mode "numeric" :max-length 3 :text-align "center" :on-change-text #(debounce-and-dispatch [:items.melee/update, i, :weight, (->int %)] 500)}]])) (conj weapons empty-weapon)))]) (rf/reg-sub :items/melee-weapons (fn [db] (get-in db [:items :melee-weapons] []))) (rf/reg-sub :skills/shields :<- [:skills/weapons] (fn [skills] (filter #(or (= :cloak (:k %)) (= :shield (keyword (namespace (:k %))))) skills))) (rf/reg-sub :skills/weapons :<- [:skills] (fn [skills] (filter #(some? ((generify-key (:k %)) (:combat-melee grouped-skills))) skills))) (rf/reg-sub :skills/parriable-weapons :<- [:skills/weapons] (fn [weapons] (->> weapons (filter #(not (or (= :cloak (:k %)) (= :shield (keyword (namespace (:k %)))))))))) (rf/reg-sub :defenses/parries :<- [:skills/weapons] :<- [:skills/lvls] (fn [[skills skill-lvls]] (some->> skills (map #(:k %)) (map #(do {% (lvl->parry (:lvl (% skill-lvls)))})) (into {})))) (rf/reg-event-fx :items.melee/update (fn [{:keys [db]} [_ i k v]] (let [weapon (merge (get-in db [:items :melee-weapons i] empty-weapon) {k v}) new-db (update-in db [:items :melee-weapons] (fnil #(do (assoc-in % [i] weapon)) [weapon]))] {:db new-db :effects.async-storage/set {:k :items/melee-weapons :value (get-in new-db [:items :melee-weapons])}})))
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // import "hardhat/console.sol"; contract NFTStore is Ownable, IERC721Receiver { ERC20 public token; IERC721 public nft; IERC721 public foundingMember; uint256[] private nftIdList; mapping(uint256 => bool) public isRegisteredId; uint16 public purchaseLimitPerUser = 1; uint256 public nftPrice; // Default 450 uint256 public nftFMPrice; // Default 400 uint256 public numberOfNTFs; mapping(address => uint16) public userPurchased; event SetPurchaseLimit(uint16 orgLimit, uint16 newLimit); event SetNFTPrice(uint256 oldPrice, uint256 newPrice); event SetNFTFMPrice(uint256 oldFMPrice, uint256 newFMPrice); event AddNFTIdList(uint256 addCount, uint256 totalCount); constructor(address _token, address _nft, address _foundingMember, uint256 _numberOfNTFs) { token = ERC20(_token); nft = IERC721(_nft); foundingMember = IERC721(_foundingMember); numberOfNTFs = _numberOfNTFs; nftPrice = 450 * (10 ** token.decimals()); nftFMPrice = 400 * (10 ** token.decimals()); } function onERC721Received( address, address, uint256, bytes calldata ) external override returns(bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } function setPurchaseLimit(uint16 newLimit) external onlyOwner { require(newLimit > 0, "Invalid value"); emit SetPurchaseLimit(purchaseLimitPerUser, newLimit); purchaseLimitPerUser = newLimit; } function setNFTPrice(uint256 newPrice) external onlyOwner { uint256 oldPrice = newPrice; nftPrice = newPrice; emit SetNFTPrice(oldPrice, nftPrice); } function setNFTFMPrice(uint256 newFMPrice) external onlyOwner { uint256 oldFMPrice = newFMPrice; nftFMPrice = newFMPrice; emit SetNFTFMPrice(oldFMPrice, nftFMPrice); } function getNFTCount() external view returns(uint256) { return nftIdList.length; } function tokenAmount() external view returns (uint256) { return token.balanceOf(address(this)); } function addNFTIdList(uint256[] calldata idList) external onlyOwner { uint256 orgCount = nftIdList.length; for (uint256 i = 0; i < idList.length; i++) { require(nft.ownerOf(idList[i]) == address(this), "Invalid nft ID"); if (!isRegisteredId[idList[i]]) { nftIdList.push(idList[i]); isRegisteredId[idList[i]] = true; } } emit AddNFTIdList(nftIdList.length - orgCount, nftIdList.length); } function buyNFT() external { uint256 userPrice = nftPrice; if(foundingMember.balanceOf(_msgSender()) > 0){ userPrice = nftFMPrice; } require(token.allowance(_msgSender(), address(this)) >= userPrice, "Token not approved"); require(nftIdList.length > 0, "No NFT for sale"); require(userPurchased[_msgSender()] < purchaseLimitPerUser, "Limited to purchase"); uint256 nftId = nftIdList[nftIdList.length - 1]; token.transferFrom(_msgSender(), address(this), userPrice); nft.safeTransferFrom(address(this), _msgSender(), nftId); userPurchased[_msgSender()]++; isRegisteredId[nftId] = false; nftIdList.pop(); } function _withdrawNFTsTo(address to, uint256 count) private { require(nftIdList.length > 0, "No NFT"); require(count <= nftIdList.length, "Exceed count"); uint256 lastIndex = nftIdList.length - 1; for (uint256 i = 0; i < count; i++) { uint256 nftId = nftIdList[lastIndex - i]; isRegisteredId[nftId] = false; nft.safeTransferFrom(address(this), to, nftId); nftIdList.pop(); } } function withdrawNFTs() external onlyOwner { _withdrawNFTsTo(owner(), nftIdList.length); } function withdrawNFTsTo(address to) external onlyOwner { _withdrawNFTsTo(to, nftIdList.length); } function withdrawSomeNFTsTo(address to, uint256 count) external onlyOwner { _withdrawNFTsTo(to, count); } function _withdrawTokensTo(address to, uint256 amount) private { require(token.balanceOf(address(this)) > 0, "No token to withdraw"); token.transfer(to, amount); } function withdrawTokens() external onlyOwner { _withdrawTokensTo(owner(), token.balanceOf(address(this))); } function withdrawTokensTo(address to) external onlyOwner { _withdrawTokensTo(to, token.balanceOf(address(this))); } }
import { Link, useNavigate } from "react-router-dom"; import { ReactSession } from "react-client-session"; import { useEffect, useState } from "react"; import "./login.css"; const Login = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const navigate = useNavigate(); useEffect(() => { if (ReactSession.get("authentication_token")) { navigate("/dashboard"); } }, []); const authenticate = () => { try { fetch("http://localhost:5000/api/auth/login", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ username, password, userType: "", }), }) .then((res) => { if (!res.ok) { throw new Error(); } else { return res.json(); } }) .then((data) => { if (data.status === "success") { ReactSession.set("authentication_token", data.message); ReactSession.set("name", data.name); ReactSession.set("userType", data.userType); ReactSession.set("username", username); navigate("/dashboard"); } else { setError("Couldn't authenticate, please try another password."); } }) .catch(() => { setError("Couldn't connect, please try again."); }); } catch { setError("Couldn't connect, please try again."); } }; return ( <> <div className="d-flex h-100 justify-content-center align-items-center"> <div className="container d-flex flex-column align-items-center" style={{ transform: "translateY(-20%)" }} > <h1 className="display text-center">Welcome to your Knetwork.</h1> <div className="card login-card" style={{ marginTop: 40 }}> <div className="login-card-badge d-flex justify-content-center align-items-center"> <i className="bi bi-person-badge text-center d-block mx-auto"></i> </div> <div className="card-body"> <h2 className="display">Log in</h2> <div className="input-group mb-3 mt-3"> <input type="text" className="form-control" placeholder="Username" aria-label="Username" value={username} onChange={(e) => setUsername(e.target.value)} /> </div> <div className="input-group mb-3"> <input type="password" className={ "form-control has-validation" + (error ? " is-invalid" : "") } placeholder="Password" aria-label="Password" aria-describedby="invalidPasswordFeedback" value={password} onChange={(e) => setPassword(e.target.value)} /> {error ? ( <div className="invalid-feedback" id="invalidPasswordFeedback" > {error} </div> ) : null} </div> <button className="btn btn-primary rounded-pill mx-auto" type="submit" onClick={authenticate} > Sign in </button> <Link to="/signup" className="link-dark text-decoration-none"> <p className="mt-2" style={{ color: "grey" }}> or create account. </p> </Link> </div> </div> </div> </div> </> ); }; export default Login;
// Styles import styles from "./UiVideo.module.css"; import cn from "classnames"; import propTypes from "prop-types"; // Hooks import { useEffect, useRef } from "react"; const UiVideo = ({ src, classes, playbackRate = 1.0 }) => { const videoRef = useRef(); useEffect(() => { videoRef.current.playbackRate = playbackRate; }, []); return ( <video className={cn(styles.video, classes)} loop autoPlay muted ref={videoRef} > <source src={src} /> </video> ); }; UiVideo.propTypes = { src: propTypes.string, classes: propTypes.string, playbackRate: propTypes.number, }; export default UiVideo;
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package scopes import ( "context" "testing" "github.com/google/uuid" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/operator" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(http)) } type http struct { kubeapi *kubernetes.Kubernetes operator *operator.Operator sub *subscriber.Subscriber daprd1 *daprd.Daprd daprd2 *daprd.Daprd } func (h *http) Setup(t *testing.T) []framework.Option { h.sub = subscriber.New(t, subscriber.WithRoutes( "/all", "/allempty", "/only1", "/only2", "/both", )) sentry := sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io")) appid1 := uuid.New().String() appid2 := uuid.New().String() h.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", sentry.Port(), ), kubernetes.WithClusterDaprComponentList(t, &compapi.ComponentList{ Items: []compapi.Component{{ ObjectMeta: metav1.ObjectMeta{Name: "mypub", Namespace: "default"}, Spec: compapi.ComponentSpec{ Type: "pubsub.in-memory", Version: "v1", }, }}, }), kubernetes.WithClusterDaprSubscriptionListV2(t, &subapi.SubscriptionList{ Items: []subapi.Subscription{ { ObjectMeta: metav1.ObjectMeta{Name: "sub1", Namespace: "default"}, Spec: subapi.SubscriptionSpec{ Pubsubname: "mypub", Topic: "all", Routes: subapi.Routes{ Default: "/all", }, }, Scopes: nil, }, { ObjectMeta: metav1.ObjectMeta{Name: "sub2", Namespace: "default"}, Spec: subapi.SubscriptionSpec{ Pubsubname: "mypub", Topic: "allempty", Routes: subapi.Routes{ Default: "/allempty", }, }, Scopes: []string{}, }, { ObjectMeta: metav1.ObjectMeta{Name: "sub3", Namespace: "default"}, Spec: subapi.SubscriptionSpec{ Pubsubname: "mypub", Topic: "only1", Routes: subapi.Routes{ Default: "/only1", }, }, Scopes: []string{appid1}, }, { ObjectMeta: metav1.ObjectMeta{Name: "sub4", Namespace: "default"}, Spec: subapi.SubscriptionSpec{ Pubsubname: "mypub", Topic: "only2", Routes: subapi.Routes{ Default: "/only2", }, }, Scopes: []string{appid2}, }, { ObjectMeta: metav1.ObjectMeta{Name: "sub5", Namespace: "default"}, Spec: subapi.SubscriptionSpec{ Pubsubname: "mypub", Topic: "both", Routes: subapi.Routes{ Default: "/both", }, }, Scopes: []string{appid1, appid2}, }, }, }), ) h.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(h.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)), ) daprdOpts := []daprd.Option{ daprd.WithMode("kubernetes"), daprd.WithSentryAddress(sentry.Address()), daprd.WithControlPlaneAddress(h.operator.Address()), daprd.WithAppPort(h.sub.Port()), daprd.WithAppProtocol("http"), daprd.WithDisableK8sSecretStore(true), daprd.WithEnableMTLS(true), daprd.WithNamespace("default"), daprd.WithControlPlaneTrustDomain("integration.test.dapr.io"), daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors), )), } h.daprd1 = daprd.New(t, append(daprdOpts, daprd.WithAppID(appid1))...) h.daprd2 = daprd.New(t, append(daprdOpts, daprd.WithAppID(appid2))...) return []framework.Option{ framework.WithProcesses(sentry, h.sub, h.kubeapi, h.operator, h.daprd1, h.daprd2), } } func (h *http) Run(t *testing.T, ctx context.Context) { h.operator.WaitUntilRunning(t, ctx) h.daprd1.WaitUntilRunning(t, ctx) h.daprd2.WaitUntilRunning(t, ctx) client1 := h.daprd1.GRPCClient(t, ctx) client2 := h.daprd2.GRPCClient(t, ctx) meta, err := client1.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.ElementsMatch(t, []*rtv1.PubsubSubscription{ {PubsubName: "mypub", Topic: "all", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/all"}}, }}, {PubsubName: "mypub", Topic: "allempty", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/allempty"}}, }}, {PubsubName: "mypub", Topic: "only1", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/only1"}}, }}, {PubsubName: "mypub", Topic: "both", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/both"}}, }}, }, meta.GetSubscriptions()) meta, err = client2.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.ElementsMatch(t, []*rtv1.PubsubSubscription{ {PubsubName: "mypub", Topic: "all", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/all"}}, }}, {PubsubName: "mypub", Topic: "allempty", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/allempty"}}, }}, {PubsubName: "mypub", Topic: "only2", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/only2"}}, }}, {PubsubName: "mypub", Topic: "both", Rules: &rtv1.PubsubSubscriptionRules{ Rules: []*rtv1.PubsubSubscriptionRule{{Path: "/both"}}, }}, }, meta.GetSubscriptions()) newReq := func(daprd *daprd.Daprd, topic string) subscriber.PublishRequest { return subscriber.PublishRequest{ Daprd: daprd, PubSubName: "mypub", Topic: topic, Data: `{"status": "completed"}`, } } h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd1, "all")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd1, "allempty")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd1, "only1")) h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd1, "only2")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd1, "both")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd2, "all")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd2, "allempty")) h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd2, "only1")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd2, "only2")) h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd2, "both")) h.sub.AssertEventChanLen(t, 0) }
"use client"; import { useState, useEffect, useContext } from "react"; // components import ThemeToggler from "./ThemeToggler"; import Logo from "./Logo"; import { usePathname } from "next/navigation"; import { LanguageContext } from "./LanguageProvider"; const header = () => { const [header, setHeader] = useState(false); const pathname = usePathname(); const { language, setLanguage } = useContext(LanguageContext); const handleLanguageChange = (newLanguage) => { setLanguage(newLanguage); localStorage.setItem("currentLang", newLanguage); setIsDropdownOpen(false); }; useEffect(() => { const scrollYPos = window.addEventListener("scroll", () => { window.scrollY > 50 ? setHeader(true) : setHeader(false); }); return () => window.removeEventListener("scroll", scrollYPos); }); const [isDropdownOpen, setIsDropdownOpen] = useState(false); useEffect(() => { const lang = localStorage.getItem("currentLang") || "no"; setLanguage(lang); }, []); return ( <header className={`${ header ? "py-4 bg-white shadow-lg dark:bg-accent" : "py-6 dark:bg-transparent" } sticky top-0 z-30 transition-all ${pathname === "/" && "bg-[#fef9f5]"}`} > <div className="container mx-auto"> <div className="flex justify-between items-center"> <Logo /> <div className="flex items-center gap-x-6"> <ThemeToggler /> <div className="relative"> <button onClick={() => setIsDropdownOpen(!isDropdownOpen)} className="flex items-center bg-blue-500 text-white px-4 py-2 rounded-md" > {language?.toUpperCase() ?? "NO"} </button> {isDropdownOpen && ( <ul className="absolute right-0 w-14 mt-2 bg-white dark:bg-black-500 shadow-lg rounded-md overflow-hidden"> {["no", "en"].map((language) => ( <li key={language} className="px-4 py-2 hover:bg-blue-500 hover:text-white cursor-pointer dark:text-black" onClick={() => handleLanguageChange(language)} > {language.toUpperCase()} </li> ))} </ul> )} </div> </div> </div> </div> </header> ); }; export default header;
<template> <section class="setting-box"> <div class="header-drawer-title">主题色设置</div> <div class="color-box" v-for="(item,index) in predefineColors" :key="index" :title="item.colorName" @click="changeTheme(item)"> <div class="color-block" :style="setBg(item.color)" ><i v-show="userSetting.themePackers==item.name" class="el-icon-check"></i></div> <div class="color-name">{{item.colorName}}</div> </div> <el-divider></el-divider> <div class="header-drawer-title">字体大小设置</div> <el-radio-group v-model="userSetting.fontSize" @change="changeSize()"> <div class="fontsize-radiobox"> <el-radio :label="12">小</el-radio><span style="font-size:12px;margin-left:14px;color:rgba(0,0,0,.65);">这里是内容示例。</span> </div> <div class="fontsize-radiobox"> <el-radio :label="14">标准</el-radio><span style="font-size:14px;color:rgba(0,0,0,.65);">这里是内容示例。</span> </div> <div class="fontsize-radiobox"> <el-radio :label="16">中</el-radio><span style="font-size:16px;margin-left:14px;color:rgba(0,0,0,.65);">这里是内容示例。</span> </div> <div class="fontsize-radiobox"> <el-radio :label="18">大</el-radio> <span style="font-size:18px;margin-left:14px;color:rgba(0,0,0,.65);">这里是内容示例。</span> </div> </el-radio-group> <el-divider></el-divider> <div class="header-drawer-title">其他设置</div> <div class="switch-fullbox"> <div class="switch-left">表格每页显示条数</div> <div class="switch-right"> <el-select v-model="userSetting.pageSize" placeholder="请选择" style="width:100px" size="small" @change="changeTablePageSize()"> <el-option v-for="(item,index) of pageSizeArr" :key="item.index" :label="item" :value="item"> </el-option> </el-select> </div> </div> <div class="switch-fullbox"> <div class="switch-left">字体设置</div> <div class="switch-right"> <el-select v-model="this.userSetting.pageSize" placeholder="请选择" style="width:100px" size="small" > <el-option v-for="(item,index) of pageSizeArr" :key="item.index" :label="item" :value="item"> </el-option> </el-select> </div> </div> <div class="switch-fullbox"> <div class="switch-left">多页签模式</div> <div class="switch-right"><el-switch v-model="gPageTabs"></el-switch></div> </div> <div class="switch-fullbox"> <div class="switch-left">固定侧边菜单</div> <div class="switch-right"><el-switch v-model="gSiteBarFixed"></el-switch></div> </div> </section> </template> <script> const version = require('element-ui/package.json').version // element-ui version from node_modules const ORIGINAL_THEME = '#409EFF' // default color export default { data () { return { gPageTabs: true, // 是否启用页面tabs gSiteBarFixed: false, // 左侧菜单是否随滚动条滚动 siteBarTheme: '', // 默认使用深色菜单 setChange: false, // 用户修改设置 userSetting: {}, predefineColors: [], // 主题色 pageSizeArr: [] // 表格分页 } }, created () { this.userSetting = this.$t.getObjLocal('userSetting') this.predefineColors = this.$g.COLORS this.pageSizeArr = this.$g.PAGE_SIZE_ARR }, methods: { // 全局用户字体设置 changeSize () { window.document.documentElement.setAttribute('data-size', this.userSetting.fontSize) this.SaveSetting() }, // 表格每页显示条数设置 changeTablePageSize () { ELEMENT.Pagination.props.pageSize.default = this.userSetting.pageSize this.SaveSetting() }, changeTheme (item) { this.userSetting.themePackers = item.name this.setTheme() this.SaveSetting() }, setBg (color) { return 'background:' + color }, SaveSetting () { this.$t.setObjLocal('userSetting', this.userSetting) this.$message.success('设置成功!', 3) }, setTheme () { const oldVal = '409EFF' const val = this.$t.setTheme(this.userSetting.themePackers)// 设置第三方或自定义模块换肤样式 if (typeof val !== 'string') return const themeCluster = this.getThemeCluster(val.replace('#', '')) const originalCluster = this.getThemeCluster(oldVal.replace('#', '')) const getHandler = (variable, id) => { return () => { const originalCluster = this.getThemeCluster( ORIGINAL_THEME.replace('#', '') ) const newStyle = this.updateStyle( this[variable], originalCluster, themeCluster ) let styleTag = document.getElementById(id) if (!styleTag) { styleTag = document.createElement('style') styleTag.setAttribute('id', id) document.head.appendChild(styleTag) } styleTag.innerText = newStyle } } const chalkHandler = getHandler('chalk', 'chalk-style') if (!this.chalk) { const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css` this.getCSSString(url, chalkHandler, 'chalk') } else { chalkHandler() } const styles = [].slice .call(document.querySelectorAll('style')) .filter((style) => { const text = style.innerText return ( new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text) ) }) styles.forEach((style) => { const { innerText } = style if (typeof innerText !== 'string') return style.innerText = this.updateStyle( innerText, originalCluster, themeCluster ) }) }, // 换肤 updateStyle (style, oldCluster, newCluster) { let newStyle = style oldCluster.forEach((color, index) => { newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index]) }) return newStyle }, getCSSString (url, callback, variable) { const xhr = new XMLHttpRequest() xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status === 200) { this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '') callback() } } xhr.open('GET', url) xhr.send() }, getThemeCluster (theme) { const tintColor = (color, tint) => { let red = parseInt(color.slice(0, 2), 16) let green = parseInt(color.slice(2, 4), 16) let blue = parseInt(color.slice(4, 6), 16) if (tint === 0) { // when primary color is in its rgb space return [red, green, blue].join(',') } else { red += Math.round(tint * (255 - red)) green += Math.round(tint * (255 - green)) blue += Math.round(tint * (255 - blue)) red = red.toString(16) green = green.toString(16) blue = blue.toString(16) return `#${red}${green}${blue}` } } const shadeColor = (color, shade) => { let red = parseInt(color.slice(0, 2), 16) let green = parseInt(color.slice(2, 4), 16) let blue = parseInt(color.slice(4, 6), 16) red = Math.round((1 - shade) * red) green = Math.round((1 - shade) * green) blue = Math.round((1 - shade) * blue) red = red.toString(16) green = green.toString(16) blue = blue.toString(16) return `#${red}${green}${blue}` } const clusters = [theme] for (let i = 0; i <= 9; i++) { clusters.push(tintColor(theme, Number((i / 10).toFixed(2)))) } clusters.push(shadeColor(theme, 0.1)) return clusters } } } </script> <style lang="scss" scoped> .el-drawer__header{margin-bottom:10px !important} .setting-box{ padding:15px; } .switch-fullbox{ height: 50px; .switch-left{float:left;font-size:14px;line-height:28px;color:rgba(0,0,0,.65);}; .switch-right{float:right}; } .dark{background:url(../../../common/images/system/pifu-dark.png) no-repeat; width:48px;height: 41px;display: inline-block;vertical-align:middle;cursor: pointer; } .light{background:url(../../../common/images/system/pifu-light.png) no-repeat; width:48px;height: 41px;display: inline-block;vertical-align:middle;cursor: pointer; margin-right:20px;} .header-drawer-title { color: rgba(0,0,0,.85); font-size: 16px; line-height: 1; margin: 15px 0; font-weight: 500; } .color-box{ display: inline-block;vertical-align: top;margin-left:10px;text-align: center;cursor: pointer;width:55px;margin-bottom:20px; .color-block{ width: 25px;margin: 0 auto; height: 25px; border-radius: 4px; padding-left: 0; padding-right: 0; text-align: center; color: #fff; font-weight: 700; line-height: 1.2; i{font-size:20px;color: #fff;} } .color-name{color:rgba(0, 0, 0, 0.65);font-size:14px;line-height: 30px;} } .check-box{padding-top: 13px;padding-left:22px;} .check-box i{font-size: 20px;color: #1890ff} .fontsize-radiobox{margin:18px 0;} </style>
import { useState } from "react"; import styled from "styled-components"; import { mobile } from "../responsive"; const Container = styled.div` width: 100vw; height: 100vh; background: url("http://wallpaperset.com/w/full/f/8/8/492379.jpg") center; background-size: cover; display: flex; align-items: center; justify-content: center; `; const Wrapper = styled.div` width: 40%; padding: 20px; background-color: white; ${mobile({ width: "75%" })}; `; const Title = styled.h2` font-size: 24px; font-weight: 300; `; const Form = styled.form` display: flex; flex-wrap: wrap; `; const Input = styled.input` flex: 1; min-width: 40%; margin: 20px 10px 0px 0px; padding: 10px; `; const Button = styled.button` width: 50%; border: none; padding: 15px 20px; background-color: teal; color: white; cursor: pointer; margin-top:10px; `; const AddProduct = () => { const [user, setUser] = useState({}); const handleAddUser = (event) => { event.preventDefault(); console.log(user); fetch("http://localhost:5000/api/products", { method: "POST", headers: { "content-type": "application/json", }, body: JSON.stringify(user), }) .then((res) => res.json()) .then((data) => { console.log(data); alert('Product added successfully'); }); }; const handleInputOnBlur = (event) => { const field = event.target.name; const value = event.target.value; const newUser = { ...user }; newUser[field] = value; setUser(newUser); console.log(newUser); }; return ( <Container> <Wrapper> <Title>ADD A NEW PRODUCT</Title> <Form onSubmit={handleAddUser}> <Input type="text" name="title" id="name" placeholder="Title Name" onBlur={handleInputOnBlur} required /> <Input type="text" name="desc" id="name" placeholder="Description" onBlur={handleInputOnBlur} required /> <Input type="url" name="imgLink" id="lastName" placeholder="Insert Image Url" onBlur={handleInputOnBlur} required /> <Input type="text" name="category" id="category" placeholder="Category" onBlur={handleInputOnBlur} required /> <Input type="text" name="size" id="size" placeholder="Size" onBlur={handleInputOnBlur} required /> <Input type="text" name="color" id="color" placeholder="Color" onBlur={handleInputOnBlur} required /> <Input type="number" name="price" id="price" placeholder="Price" onBlur={handleInputOnBlur} required /> <Button type="submit">CREATE</Button> </Form> </Wrapper> </Container> ); }; export default AddProduct;
#pragma once #pragma once #include <list> #include <string> #include <SFML/Graphics/Transform.hpp> #include <utility> #include "IComponent.h" class GameObject:public Transformable { public: using ptr = std::shared_ptr<GameObject>; GameObject(std::string id) : m_id(std::move(id)) { } /// Add a component to the game object. Internally the game object /// identifies if it's a drawable component to call it's draw /// function or a general update component to call it's update /// function. /// \param component the component void addComponent(const IComponent::ptr& component); /// Returns the component of the given type template <typename TComponent> std::shared_ptr<TComponent> getComponent() { for (auto component : m_componentList) { if (std::shared_ptr<TComponent> cmp = std::dynamic_pointer_cast<TComponent>(component)) { return cmp; } } return nullptr; } /// Initialize all added components bool init(); /// Could also be moved out of game object in the long run. void update(float deltaTime); //// TODO: implement deletion mechanism bool isMarkedForDelete() const { return m_WantToDie; } void markForDelete() { m_WantToDie = true; } std::string getId() const { return m_id; } void setId(const std::string& id) { m_id = id; } protected: std::string m_id = "unnamed"; //< unique name of object, e.g., player bool m_WantToDie = false; std::list<IComponent::ptr> m_componentList; };
import { BotCommand, Message, ZTelBot, fileFromPath } from '../../src'; import getApiToken from '../util/getApiToken'; import path from 'path'; it('should get info of bot', async () => { const telBot = new ZTelBot({ token: getApiToken() }); const response = await telBot.getMe(); expect(response.username).toMatch(/bot/gi); expect(response).toHaveProperty('firstName'); }); it('should get updates of bot', async () => { const telBot = new ZTelBot({ token: getApiToken() }); await telBot.getUpdates(); }); it('should send a message', async () => { const telBot = new ZTelBot({ token: getApiToken() }); const message = await telBot.sendMessage({ chatId: process.env.TEST_CHAT_ID || '', text: 'Teste' }); expect(message).toHaveProperty('text'); }); it('should send an audio', async () => { const telBot = new ZTelBot({ token: getApiToken() }); const message = await telBot.sendAudio({ chatId: process.env.TEST_CHAT_ID || '', audio: fileFromPath(path.resolve('./test/resources/test.mp3')) }); expect(message).toBeDefined(); }); it('should send a javascript code', async () => { const telBot = new ZTelBot({ token: getApiToken() }); const message = await telBot.sendMessage({ chatId: process.env.TEST_CHAT_ID || '', text: '```javascript\r\nconsole.log("Hello world");\r\n```', parseMode: 'MarkdownV2' }); expect(message).toHaveProperty('text'); }); it('should listen a sent message', async () => { const telBot = new ZTelBot({ token: getApiToken() }); const text = '2 + 2 + 0'; let result: Message = new Message(); telBot.addSentMessageListener(evt => { result = evt.message || result; }); await telBot.sendMessage({ chatId: process.env.TEST_CHAT_ID || '', text }); expect(result.text).toBe(text); }); it('should set and get my commands', async () => { const telBot = new ZTelBot({ token: getApiToken() }); const commands: BotCommand[] = [ { command: 'hi', description: 'Send hi' }, { command: 'test', description: 'test some thing' } ]; const response = await telBot.setMyCommands(commands); const myCommands = await telBot.getMyCommands(); expect(response).toBeTruthy(); expect(commands).toStrictEqual(myCommands); });
document.getElementById("searchInput").addEventListener("keydown", function(event) { if (event.key === "Enter") { searchMovie(); } }); function searchMovie() { var searchTerm = document.getElementById("searchInput").value.trim(); if (searchTerm === "") { alert("Please enter a movie title."); return; } var xhr = new XMLHttpRequest(); xhr.open("GET", "http://www.omdbapi.com/?apikey=b31db97e&t=" + searchTerm, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); if (response.Response === "True") { displayResult(response); } else { alert("Movie not found!"); } } }; xhr.send(); } function displayResult(data) { var movieDetailsDiv = document.getElementById("movieDetails"); movieDetailsDiv.style.color = "white"; var resultHTML = "<p><b>Title: " + data.Title + "</p>" + "<p>Year: " + data.Year + "</p>" + "<p>Rated: " + data.Rated + "</p>" + "<p>Released: " + data.Released + "</p>" + "<p>Runtime: " + data.Runtime + "</p>" + "<img src='" + data.Poster + "' alt='" + data.Title + " Poster' style='max-width: 100%;'>" + "<p>Genre: " + data.Genre + "</p>" + "<p>Director: " + data.Director + "</p>" + "<p>Actors: " + data.Actors + "</p>" + "<p>Plot: " + data.Plot + "</p>"; movieDetailsDiv.innerHTML = resultHTML; }
<?php namespace App\Form; use App\Entity\Ingredient; use App\Entity\Recipe; use App\Repository\IngredientRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Extension\Core\Type\RangeType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Constraints as Assert; use Vich\UploaderBundle\Form\Type\VichFileType; class RecipeType extends AbstractType { private TokenStorageInterface $token; public function __construct(TokenStorageInterface $token) { $this->token = $token; } public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('name', TextType::class, [ 'attr'=>[ 'class'=>'form-control', 'minlength'=>'2', 'maxlength'=>'50' ], 'label' => 'Nom', 'label_attr' => [ 'class' => 'form-label mt-4' ], 'constraints'=>[ new Assert\Length(['min'=>2, 'max' => 50]), new Assert\NotBlank() ] ]) ->add('time', IntegerType::class,[ 'attr'=>[ 'class'=>'form-control', 'min'=>1, 'max'=>1440, ], 'required' => false, 'label'=>'Time in minutes', 'label_attr'=>[ 'class'=>'form-label mt-4' ], 'constraints'=>[ new Assert\LessThan(1441), new Assert\Positive() ] ]) ->add('nbPeople',IntegerType::class,[ 'attr'=>[ 'class'=>'form-control', 'min'=>1, 'max'=>50, ], 'required' => false, 'label'=>'Number of person', 'label_attr'=>[ 'class'=>'form-label mt-4' ], 'constraints'=>[ new Assert\LessThan(51), new Assert\Positive() ] ]) ->add('difficulty',RangeType::class,[ 'attr'=>[ 'class'=>'form-range', 'min'=>1, 'max'=>5, ], 'label'=>'Difficulty', 'label_attr'=>[ 'class'=>'form-label mt-4' ], 'constraints'=>[ new Assert\LessThan(6), new Assert\Positive() ] ]) ->add('description',TextareaType::class,[ 'attr'=>[ 'class'=>'form-control', 'min'=>1, 'max'=>5, ], 'label'=>'Description', 'label_attr'=>[ 'class'=>'form-label mt-4' ], 'constraints'=>[ new Assert\NotBlank(), ] ]) ->add('price',MoneyType::class,[ 'attr'=>[ 'class'=>'form-control', ], 'label' => 'Prix', 'label_attr' => [ 'class' => 'form-label mt-4' ], 'constraints'=>[ new Assert\Positive(), new Assert\LessThan(1001) ] ]) ->add('isFavourite',CheckboxType::class,[ 'attr'=>[ 'class'=>'form-check-input"', ], 'required' => false, 'label' => 'Favoris', 'label_attr' => [ 'class' => "form-check-label mt-4" ], 'constraints'=>[ new Assert\NotNull(), ] ]) ->add('ingredients',EntityType::class,[ 'class'=>Ingredient::class, 'query_builder' => function(IngredientRepository $r){ return $r->createQueryBuilder('i' ) ->where('i.user = :user') ->orderBy('i.name','ASC') ->setParameter('user', $this->token->getToken()->getUser()); }, 'label' => 'Les ingrédients', 'label_attr' => [ 'class' => 'form-label mt-4' ], 'choice_label' => 'name', 'multiple' => true, 'expanded' => true, ]) ->add('imageFile',VichFileType::class,[ 'label'=>"Image de la recette", 'label_attr'=>[ "class" => "form-label mt-4" ], 'attr' =>[ 'class'=>'btn btn-primary mt-4' ] ]) ->add('submit',SubmitType::class,[ 'attr' =>[ 'class'=>'btn btn-primary mt-4' ], 'label'=>'Enregistrer' ]); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Recipe::class, ]); } }
from IExpectedScoreCalculator import IExpectedScoreCalculator from Player import Player import pandas as pd class PLExpectedScoreCalculator(IExpectedScoreCalculator): def __init__(self, gw: int) -> None: super().__init__() self.gw = gw def calculate_expected_score(self, player: Player) -> float: """ Calculate expected score based on Premier Leagues expected score announcement Expected scores are at Data/2023-24/gws/xP{self.gw}.csv Players expected score is in the xP column correspond to players id. """ # Path to the CSV file file_path = f"Data/2023-24/gws/xP{self.gw}.csv" # Load the data data = pd.read_csv(file_path) # Find the expected score for the player player_data = data[data['id'] == player.id] if not player_data.empty: return player_data['xP'].iloc[0] else: # Return -100 if the player's data is not found return -100.0
# Copyright (c) 2023 ETH Zurich, Christian R. Steger # MIT License cimport numpy as np import numpy as np import os # ----------------------------------------------------------------------------- # Compute sky view factor # ----------------------------------------------------------------------------- cdef extern from "horizon_comp.h": void sky_view_factor_comp( float* vert_grid, int dem_dim_0, int dem_dim_1, float* vert_grid_in, int dem_dim_in_0, int dem_dim_in_1, double* north_pole, double* sky_view_factor, double* area_increase_factor, double* sky_view_area_factor, double* slope, double* aspect, int pixel_per_gc, int offset_gc, np.npy_uint8* mask, float dist_search, int hori_azim_num, double hori_acc, char* ray_algorithm, double elev_ang_low_lim, char* geom_type) def sky_view_factor( np.ndarray[np.float32_t, ndim = 1] vert_grid, int dem_dim_0, int dem_dim_1, np.ndarray[np.float32_t, ndim = 1] vert_grid_in, int dem_dim_in_0, int dem_dim_in_1, np.ndarray[np.float64_t, ndim = 1] north_pole, int pixel_per_gc, int offset_gc, np.ndarray[np.uint8_t, ndim = 2] mask=None, float dist_search=100.0, int hori_azim_num=90, double hori_acc=1.0, str ray_algorithm="guess_constant", double elev_ang_low_lim = -15.0, str geom_type="grid"): """Compute the sky view factor. Parameters ---------- vert_grid : ndarray of float Array (one-dimensional) with vertices of DEM in ENU coordinates [metre] dem_dim_0 : int Dimension length of DEM in y-direction dem_dim_1 : int Dimension length of DEM in x-direction vert_grid_in : ndarray of float Array (one-dimensional) with vertices of inner DEM with 0.0 m elevation in ENU coordinates [metre] dem_dim_in_0 : int Dimension length of inner DEM in y-direction dem_dim_in_1 : int Dimension length of inner DEM in x-direction north_pole : ndarray of double Array (one-dimensional) with ENU coordinates (x, y, z) of North Pole pixel_per_gc : int Number of subgrid pixels within one grid cell (along one dimension) offset_gc : int Offset number of grid cells mask : ndarray of uint8 Array (two-dimensional) with grid cells for which 'sw_dir_cor' and 'sky_view_factor' are computed. Masked (0) grid cells are filled with NaN. dist_search : float Search distance for topographic shadowing [kilometre] hori_azim_num : int Number of azimuth sectors for horizon computation hori_acc : double Accuracy of horizon computation [degree] ray_algorithm : str Algorithm for horizon detection (discrete_sampling, binary_search, guess_constant) elev_ang_low_lim : double Lower limit for elevation angle search [degree] geom_type : str Embree geometry type (triangle, quad, grid) Returns ------- sky_view_factor : ndarray of double Array (two-dimensional) with sky view factor (y, x) [-] area_increase_factor : ndarray of double Array (two-dimensional) with surface area increase factor (due to sloped terrain) [-] sky_view_area_factor : ndarray of double Array (two-dimensional) with 'sky_view_factor' divided by 'area_increase_factor' [-] slope : ndarray of double Array (two-dimensional) with surface slope [degree] aspect : ndarray of double Array (two-dimensional) with surface aspect (clockwise from North) [degree] References ---------- - Manners, J., Vosper, S.B. and Roberts, N. (2012): Radiative transfer over resolved topographic features for high-resolution weather prediction, Q.J.R. Meteorol. Soc., 138: 720-733. - Steger, C. R., Steger, B., and Schär, C. (2022): HORAYZON v1.2: an efficient and flexible ray-tracing algorithm to compute horizon and sky view factor, Geosci. Model Dev., 15, 6817–6840.""" # Check consistency and validity of input arguments if ((dem_dim_0 != (2 * offset_gc * pixel_per_gc) + dem_dim_in_0) or (dem_dim_1 != (2 * offset_gc * pixel_per_gc) + dem_dim_in_1)): raise ValueError("Inconsistency between input arguments 'dem_dim_?'," + " 'dem_dim_in_?', 'offset_gc' and 'pixel_per_gc'") if len(vert_grid) < (dem_dim_0 * dem_dim_1 * 3): raise ValueError("array 'vert_grid' has insufficient length") if len(vert_grid_in) < (dem_dim_in_0 * dem_dim_in_1 * 3): raise ValueError("array 'vert_grid_in' has insufficient length") if pixel_per_gc < 1: raise ValueError("value for 'pixel_per_gc' must be larger than 1") if offset_gc < 0: raise ValueError("value for 'offset_gc' must be larger than 0") num_gc_y = int((dem_dim_0 - 1) / pixel_per_gc) - 2 * offset_gc num_gc_x = int((dem_dim_1 - 1) / pixel_per_gc) - 2 * offset_gc if mask is None: mask = np.ones((num_gc_y, num_gc_x), dtype=np.uint8) if (mask.shape[0] != num_gc_y) or (mask.shape[1] != num_gc_x): raise ValueError("shape of mask is inconsistent with other input") if mask.dtype != "uint8": raise TypeError("data type of mask must be 'uint8'") if dist_search < 0.1: raise ValueError("'dist_search' must be at least 100.0 m") if hori_acc > 10.0: raise ValueError("limit (10 degree) of 'hori_acc' exceeded") if ray_algorithm not in ("discrete_sampling", "binary_search", "guess_constant"): raise ValueError("invalid input argument for ray_algorithm") if geom_type not in ("triangle", "quad", "grid"): raise ValueError("invalid input argument for geom_type") # Check size of input geometries if (dem_dim_0 > 32767) or (dem_dim_1 > 32767): raise ValueError("maximal allowed input length for dem_dim_0 and " "dem_dim_1 is 32'767") # Ensure that passed arrays are contiguous in memory vert_grid = np.ascontiguousarray(vert_grid) vert_grid_in = np.ascontiguousarray(vert_grid_in) # Convert input strings to bytes ray_algorithm_c = ray_algorithm.encode("utf-8") geom_type_c = geom_type.encode("utf-8") # Allocate array for shortwave correction factors cdef int len_in_0 = int((dem_dim_in_0 - 1) / pixel_per_gc) cdef int len_in_1 = int((dem_dim_in_1 - 1) / pixel_per_gc) cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ sky_view_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ area_increase_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) area_increase_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ sky_view_area_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_area_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ slope = np.empty((len_in_0, len_in_1), dtype=np.float64) cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ aspect = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_factor_comp( &vert_grid[0], dem_dim_0, dem_dim_1, &vert_grid_in[0], dem_dim_in_0, dem_dim_in_1, &north_pole[0], &sky_view_factor[0, 0], &area_increase_factor[0, 0], &sky_view_area_factor[0, 0], &slope[0, 0], &aspect[0, 0], pixel_per_gc, offset_gc, &mask[0, 0], dist_search, hori_azim_num, hori_acc, ray_algorithm_c, elev_ang_low_lim, geom_type_c) return sky_view_factor, area_increase_factor, sky_view_area_factor, \ slope, aspect # ----------------------------------------------------------------------------- # Compute sky view factor and SW_dir correction factor # ----------------------------------------------------------------------------- cdef extern from "horizon_comp.h": void sky_view_factor_sw_dir_cor_comp( float* vert_grid, int dem_dim_0, int dem_dim_1, float* vert_grid_in, int dem_dim_in_0, int dem_dim_in_1, double* north_pole, double* sun_pos, int dim_sun_0, int dim_sun_1, float* sw_dir_cor, double* sky_view_factor, double* area_increase_factor, double* sky_view_area_factor, double* slope, double* aspect, int pixel_per_gc, int offset_gc, np.npy_uint8* mask, float dist_search, int hori_azim_num, double hori_acc, char* ray_algorithm, double elev_ang_low_lim, char* geom_type, double sw_dir_cor_max, double ang_max) def sky_view_factor_sw_dir_cor( np.ndarray[np.float32_t, ndim = 1] vert_grid, int dem_dim_0, int dem_dim_1, np.ndarray[np.float32_t, ndim = 1] vert_grid_in, int dem_dim_in_0, int dem_dim_in_1, np.ndarray[np.float64_t, ndim = 1] north_pole, np.ndarray[np.float64_t, ndim = 3] sun_pos, int pixel_per_gc, int offset_gc, np.ndarray[np.uint8_t, ndim = 2] mask=None, float dist_search=100.0, int hori_azim_num=90, double hori_acc=1.0, str ray_algorithm="guess_constant", double elev_ang_low_lim = -15.0, str geom_type="grid", double sw_dir_cor_max=25.0, double ang_max=89.9): """Compute subsolar lookup table of subgrid-scale correction factors for direct downward shortwave radiation. Additionally, the sky view factor is computed. Parameters ---------- vert_grid : ndarray of float Array (one-dimensional) with vertices of DEM in ENU coordinates [metre] dem_dim_0 : int Dimension length of DEM in y-direction dem_dim_1 : int Dimension length of DEM in x-direction vert_grid_in : ndarray of float Array (one-dimensional) with vertices of inner DEM with 0.0 m elevation in ENU coordinates [metre] dem_dim_in_0 : int Dimension length of inner DEM in y-direction dem_dim_in_1 : int Dimension length of inner DEM in x-direction north_pole : ndarray of double Array (one-dimensional) with ENU coordinates (x, y, z) of North Pole sun_pos : ndarray of double Array (three-dimensional) with sun positions in ENU coordinates (dim_sun_0, dim_sun_1, 3) [metre] pixel_per_gc : int Number of subgrid pixels within one grid cell (along one dimension) offset_gc : int Offset number of grid cells mask : ndarray of uint8 Array (two-dimensional) with grid cells for which 'sw_dir_cor' and 'sky_view_factor' are computed. Masked (0) grid cells are filled with NaN. dist_search : float Search distance for topographic shadowing [kilometre] hori_azim_num : int Number of azimuth sectors for horizon computation hori_acc : double Accuracy of horizon computation [degree] ray_algorithm : str Algorithm for horizon detection (discrete_sampling, binary_search, guess_constant) elev_ang_low_lim : double Lower limit for elevation angle search [degree] geom_type : str Embree geometry type (triangle, quad, grid) sw_dir_cor_max : double Maximal allowed correction factor for direct downward shortwave radiation [-] ang_max : double Maximal angle between sun vector and horizontal surface normal for which correction is computed. For larger angles, 'sw_dir_cor' is set to 0.0 [degree] Returns ------- sw_dir_cor : ndarray of float Array (four-dimensional) with shortwave correction factor (y, x, dim_sun_0, dim_sun_1) [-] sky_view_factor : ndarray of double Array (two-dimensional) with sky view factor (y, x) [-] area_increase_factor : ndarray of double Array (two-dimensional) with surface area increase factor (due to sloped terrain) [-] sky_view_area_factor : ndarray of double Array (two-dimensional) with 'sky_view_factor' divided by 'area_increase_factor' [-] slope : ndarray of double Array (two-dimensional) with surface slope [degree] aspect : ndarray of double Array (two-dimensional) with surface aspect (clockwise from North) [degree] References ---------- - Mueller, M. D. and Scherer, D. (2005): A Grid- and Subgrid-Scale Radiation Parameterization of Topographic Effects for Mesoscale Weather Forecast Models, Monthly Weather Review, 133(6), 1431-1442. - Manners, J., Vosper, S.B. and Roberts, N. (2012): Radiative transfer over resolved topographic features for high-resolution weather prediction, Q.J.R. Meteorol. Soc., 138: 720-733. - Steger, C. R., Steger, B., and Schär, C. (2022): HORAYZON v1.2: an efficient and flexible ray-tracing algorithm to compute horizon and sky view factor, Geosci. Model Dev., 15, 6817–6840.""" # Check consistency and validity of input arguments if ((dem_dim_0 != (2 * offset_gc * pixel_per_gc) + dem_dim_in_0) or (dem_dim_1 != (2 * offset_gc * pixel_per_gc) + dem_dim_in_1)): raise ValueError("Inconsistency between input arguments 'dem_dim_?'," + " 'dem_dim_in_?', 'offset_gc' and 'pixel_per_gc'") if len(vert_grid) < (dem_dim_0 * dem_dim_1 * 3): raise ValueError("array 'vert_grid' has insufficient length") if len(vert_grid_in) < (dem_dim_in_0 * dem_dim_in_1 * 3): raise ValueError("array 'vert_grid_in' has insufficient length") if pixel_per_gc < 1: raise ValueError("value for 'pixel_per_gc' must be larger than 1") if offset_gc < 0: raise ValueError("value for 'offset_gc' must be larger than 0") num_gc_y = int((dem_dim_0 - 1) / pixel_per_gc) - 2 * offset_gc num_gc_x = int((dem_dim_1 - 1) / pixel_per_gc) - 2 * offset_gc if mask is None: mask = np.ones((num_gc_y, num_gc_x), dtype=np.uint8) if (mask.shape[0] != num_gc_y) or (mask.shape[1] != num_gc_x): raise ValueError("shape of mask is inconsistent with other input") if mask.dtype != "uint8": raise TypeError("data type of mask must be 'uint8'") if dist_search < 0.1: raise ValueError("'dist_search' must be at least 100.0 m") if hori_acc > 10.0: raise ValueError("limit (10 degree) of 'hori_acc' exceeded") if ray_algorithm not in ("discrete_sampling", "binary_search", "guess_constant"): raise ValueError("invalid input argument for ray_algorithm") if geom_type not in ("triangle", "quad", "grid"): raise ValueError("invalid input argument for geom_type") if (sw_dir_cor_max < 2.0) or (sw_dir_cor_max > 100.0): raise ValueError("'sw_dir_cor_max' must be in the range [2.0, 100.0]") if (ang_max < 89.0) or (ang_max >= 90.0): raise ValueError("'ang_max' must be in the range [89.0, <90.0]") # Check size of input geometries if (dem_dim_0 > 32767) or (dem_dim_1 > 32767): raise ValueError("maximal allowed input length for dem_dim_0 and " "dem_dim_1 is 32'767") # Ensure that passed arrays are contiguous in memory vert_grid = np.ascontiguousarray(vert_grid) vert_grid_in = np.ascontiguousarray(vert_grid_in) sun_pos = np.ascontiguousarray(sun_pos) # Convert input strings to bytes ray_algorithm_c = ray_algorithm.encode("utf-8") geom_type_c = geom_type.encode("utf-8") # Allocate array for shortwave correction factors cdef int len_in_0 = int((dem_dim_in_0 - 1) / pixel_per_gc) cdef int len_in_1 = int((dem_dim_in_1 - 1) / pixel_per_gc) cdef int dim_sun_0 = sun_pos.shape[0] cdef int dim_sun_1 = sun_pos.shape[1] cdef np.ndarray[np.float32_t, ndim = 4, mode = "c"] \ sw_dir_cor = np.empty((len_in_0, len_in_1, dim_sun_0, dim_sun_1), dtype=np.float32) sw_dir_cor.fill(0.0) # -> ensure that all elements of array 'sw_dir_cor' are 0.0 (crucial # because subgrid correction values are iteratively added) -> probably no longer needed with horizon... cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ sky_view_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ area_increase_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) area_increase_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ sky_view_area_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_area_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ slope = np.empty((len_in_0, len_in_1), dtype=np.float64) cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ aspect = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_factor_sw_dir_cor_comp( &vert_grid[0], dem_dim_0, dem_dim_1, &vert_grid_in[0], dem_dim_in_0, dem_dim_in_1, &north_pole[0], &sun_pos[0, 0, 0], dim_sun_0, dim_sun_1, &sw_dir_cor[0, 0, 0, 0], &sky_view_factor[0, 0], &area_increase_factor[0, 0], &sky_view_area_factor[0, 0], &slope[0, 0], &aspect[0, 0], pixel_per_gc, offset_gc, &mask[0, 0], dist_search, hori_azim_num, hori_acc, ray_algorithm_c, elev_ang_low_lim, geom_type_c, sw_dir_cor_max, ang_max) return sw_dir_cor, sky_view_factor, \ area_increase_factor, sky_view_area_factor, \ slope, aspect # ----------------------------------------------------------------------------- # Compute sky view factor and average distance to terrain # ----------------------------------------------------------------------------- cdef extern from "horizon_comp.h": void sky_view_factor_dist_comp( float* vert_grid, int dem_dim_0, int dem_dim_1, float* vert_grid_in, int dem_dim_in_0, int dem_dim_in_1, double* north_pole, double* sky_view_factor, double* area_increase_factor, double* sky_view_area_factor, double* slope, double* aspect, double * distance, int pixel_per_gc, int offset_gc, np.npy_uint8* mask, float dist_search, int azim_num, int elev_num, char* geom_type) def sky_view_factor_dist( np.ndarray[np.float32_t, ndim = 1] vert_grid, int dem_dim_0, int dem_dim_1, np.ndarray[np.float32_t, ndim = 1] vert_grid_in, int dem_dim_in_0, int dem_dim_in_1, np.ndarray[np.float64_t, ndim = 1] north_pole, int pixel_per_gc, int offset_gc, np.ndarray[np.uint8_t, ndim = 2] mask=None, float dist_search=100.0, int azim_num=45, int elev_num=30, str geom_type="grid"): """Compute the sky view factor and the average distance to the terrain. Parameters ---------- vert_grid : ndarray of float Array (one-dimensional) with vertices of DEM in ENU coordinates [metre] dem_dim_0 : int Dimension length of DEM in y-direction dem_dim_1 : int Dimension length of DEM in x-direction vert_grid_in : ndarray of float Array (one-dimensional) with vertices of inner DEM with 0.0 m elevation in ENU coordinates [metre] dem_dim_in_0 : int Dimension length of inner DEM in y-direction dem_dim_in_1 : int Dimension length of inner DEM in x-direction north_pole : ndarray of double Array (one-dimensional) with ENU coordinates (x, y, z) of North Pole pixel_per_gc : int Number of subgrid pixels within one grid cell (along one dimension) offset_gc : int Offset number of grid cells mask : ndarray of uint8 Array (two-dimensional) with grid cells for which 'sw_dir_cor' and 'sky_view_factor' are computed. Masked (0) grid cells are filled with NaN. dist_search : float Search distance for topographic shadowing [kilometre] azim_num : int Number of sampling along azimuth angle elev_num : int Number of sampling along elevation angle geom_type : str Embree geometry type (triangle, quad, grid) Returns ------- sky_view_factor : ndarray of double Array (two-dimensional) with sky view factor (y, x) [-] area_increase_factor : ndarray of double Array (two-dimensional) with surface area increase factor (due to sloped terrain) [-] sky_view_area_factor : ndarray of double Array (two-dimensional) with 'sky_view_factor' divided by 'area_increase_factor' [-] slope : ndarray of double Array (two-dimensional) with surface slope [degree] aspect : ndarray of double Array (two-dimensional) with surface aspect (clockwise from North) [degree] distance : ndarray of double Array (two-dimensional) with average distance to the terrain [metre] References ---------- - Manners, J., Vosper, S.B. and Roberts, N. (2012): Radiative transfer over resolved topographic features for high-resolution weather prediction, Q.J.R. Meteorol. Soc., 138: 720-733. - Steger, C. R., Steger, B., and Schär, C. (2022): HORAYZON v1.2: an efficient and flexible ray-tracing algorithm to compute horizon and sky view factor, Geosci. Model Dev., 15, 6817–6840.""" # Check consistency and validity of input arguments if ((dem_dim_0 != (2 * offset_gc * pixel_per_gc) + dem_dim_in_0) or (dem_dim_1 != (2 * offset_gc * pixel_per_gc) + dem_dim_in_1)): raise ValueError("Inconsistency between input arguments 'dem_dim_?'," + " 'dem_dim_in_?', 'offset_gc' and 'pixel_per_gc'") if len(vert_grid) < (dem_dim_0 * dem_dim_1 * 3): raise ValueError("array 'vert_grid' has insufficient length") if len(vert_grid_in) < (dem_dim_in_0 * dem_dim_in_1 * 3): raise ValueError("array 'vert_grid_in' has insufficient length") if pixel_per_gc < 1: raise ValueError("value for 'pixel_per_gc' must be larger than 1") if offset_gc < 0: raise ValueError("value for 'offset_gc' must be larger than 0") num_gc_y = int((dem_dim_0 - 1) / pixel_per_gc) - 2 * offset_gc num_gc_x = int((dem_dim_1 - 1) / pixel_per_gc) - 2 * offset_gc if mask is None: mask = np.ones((num_gc_y, num_gc_x), dtype=np.uint8) if (mask.shape[0] != num_gc_y) or (mask.shape[1] != num_gc_x): raise ValueError("shape of mask is inconsistent with other input") if mask.dtype != "uint8": raise TypeError("data type of mask must be 'uint8'") if dist_search < 0.1: raise ValueError("'dist_search' must be at least 100.0 m") if geom_type not in ("triangle", "quad", "grid"): raise ValueError("invalid input argument for geom_type") # Check size of input geometries if (dem_dim_0 > 32767) or (dem_dim_1 > 32767): raise ValueError("maximal allowed input length for dem_dim_0 and " "dem_dim_1 is 32'767") # Ensure that passed arrays are contiguous in memory vert_grid = np.ascontiguousarray(vert_grid) vert_grid_in = np.ascontiguousarray(vert_grid_in) # Convert input strings to bytes geom_type_c = geom_type.encode("utf-8") # Allocate array for shortwave correction factors cdef int len_in_0 = int((dem_dim_in_0 - 1) / pixel_per_gc) cdef int len_in_1 = int((dem_dim_in_1 - 1) / pixel_per_gc) cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ sky_view_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ area_increase_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) area_increase_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ sky_view_area_factor = np.empty((len_in_0, len_in_1), dtype=np.float64) sky_view_area_factor.fill(0.0) # accumulated over pixels cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ slope = np.empty((len_in_0, len_in_1), dtype=np.float64) cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ aspect = np.empty((len_in_0, len_in_1), dtype=np.float64) cdef np.ndarray[np.float64_t, ndim = 2, mode = "c"] \ distance = np.empty((len_in_0, len_in_1), dtype=np.float64) distance.fill(0.0) # accumulated over pixels sky_view_factor_dist_comp( &vert_grid[0], dem_dim_0, dem_dim_1, &vert_grid_in[0], dem_dim_in_0, dem_dim_in_1, &north_pole[0], &sky_view_factor[0, 0], &area_increase_factor[0, 0], &sky_view_area_factor[0, 0], &slope[0, 0], &aspect[0, 0], &distance[0, 0], pixel_per_gc, offset_gc, &mask[0, 0], dist_search, azim_num, elev_num, geom_type_c) return sky_view_factor, area_increase_factor, sky_view_area_factor, \ slope, aspect, distance
<!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>Portfolio</title> <link rel="stylesheet" href="./index.html" /> <link rel="stylesheet" href="./css/styles.css" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@800&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet" /> </head> <body> <!-- Header --> <header> <nav> <a href="./index.html" class="logo" >WEB<span class="logo-second">STUDIO</span></a > <ul class="site-nav"> <li><a href="./index.html" class="link current">Studio</a></li> <li><a href="./portfolio.html" class="link">Portfolio</a></li> <li><a href="" class="link">Contacts</a></li> </ul> </nav> <address> <ul class="address-pages"> <li> <a href="mailto:[email protected]" class="mail link" >[email protected]</a > </li> <li> <a href="tel:+110001111111" class="phone link" >+11 (000) 111-11-11</a > </li> </ul> </address> </header> <main> <section class="section"> <h1 hidden>Our portfolio</h1> <ul class="list"> <li><button class="portfolio-button" type="button">All</button></li> <li> <button class="portfolio-button" type="button">Web Site</button> </li> <li><button class="portfolio-button" type="button">App</button></li> <li> <button class="portfolio-button" type="button">Design</button> </li> <li> <button class="portfolio-button" type="button">Marketing</button> </li> </ul> <ul class="list"> <li class="portfolio-list"> <a class="portfolio-links" href=""> <img src="./images/portfolio/bank-app.jpg" alt="banking app" width="360" height="300" /> <h2 class="section-subtitle">Banking App Interface Concept</h2> <p class="section-text">App</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/cashless-payment.jpg" alt="cashless payment" width="360" height="300" /> <h2 class="section-subtitle">Cashless Payment</h2> <p class="section-text">Marketing</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/meditation-app.jpg" alt="meditation app" width="360" height="300" /> <h2 class="section-subtitle">Meditation App</h2> <p class="section-text">App</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/taxi-service.jpg" alt="taxi service" width="360" height="300" /> <h2 class="section-subtitle">Taxi Service</h2> <p class="section-text">Marketing</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/screen-illustrations.jpg" alt="screen illustrations" width="360" height="300" /> <h2 class="section-subtitle">Screen Illustrations</h2> <p class="section-text">Design</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/online-courses.jpg" alt="online courses" width="360" height="300" /> <h2 class="section-subtitle">Online Courses</h2> <p class="section-text">Marketing</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/instagram-stories.jpg" alt="instagram stories concept" width="360" height="300" /> <h2 class="section-subtitle">Instagram Stories Concept</h2> <p class="section-text">Design</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/organic-food.jpg" alt="organic food" width="360" height="300" /> <h2 class="section-subtitle">Organic Food</h2> <p class="section-text">Web Site</p> </a> </li> <li> <a class="portfolio-links" href=""> <img src="./images/portfolio/fresh-coffee.jpg" alt="cup of coffee" width="360" height="300" /> <h2 class="section-subtitle">Fresh Coffee</h2> <p class="section-text">Web Site</p> </a> </li> </ul> </section> </main> <footer class="footer"> <a href="./index.html" class="logo" >WEB<span class="logo-second">STUDIO</span></a > <p class="footer-text"> Increase the flow of customers and sales for your business with digital marketing & growth solutions. </p> </footer> </body> </html>
import 'package:frontend/Test/model/question_model.dart'; class ReadingModel { int id; int test; String title; String text; int difficultyLevel; List<QuestionModel> questions; ReadingModel({ required this.id, required this.test, required this.title, required this.text, required this.difficultyLevel, required this.questions, }); factory ReadingModel.fromJson(json) { if (json == null) { return ReadingModel( id: 0, test: 0, title: '', text: '', difficultyLevel: 0, questions: [], ); } List<QuestionModel> q = []; for (var item in json['questions']) { q.add(QuestionModel.fromJson(item)); } return ReadingModel( id: json['id'], test: json['test'], title: json['title'], text: json['text'], difficultyLevel: json['difficulty_level'], questions: q, ); } }
import { useState, useRef, useEffect } from "react"; import Note from "./components/Note"; import Filter from "./components/Filter"; import NoteList from "./components/NoteList"; //import axios from "axios"; import ToggleImportant from "./components/ToggleImportant "; import noteService from "./services/notes"; import Notification from "./components/Notification"; import Footer from "./components/Footer"; const App = () => { const inputRef = useRef(null); useEffect(() => { inputRef.current.focus(); }, []); //debugger; const [notes, setNotes] = useState([]); const [newNote, setNewNote] = useState(""); const [showAll, setShowAll] = useState(true); const [filter, setFilter] = useState(""); const [errorMessage, setErrorMessage] = useState('some error happened...') /* useEffect(() => { console.log("effect"); axios.get("http://localhost:3001/notes").then((response) => { console.log("promise fulfilled"); setNotes(response.data); }); }, []); */ const hook = () => { //axios.get("http://localhost:3001/notes") noteService .getAll() /* .then(response => { setNotes(response.data) */ .then((initialNotes) => { setNotes(initialNotes); }); }; useEffect(hook, []); //console.log("render", notes.length, "notes"); const addNote = (event) => { event.preventDefault(); const noteObject = { content: newNote, important: Math.random() < 0.5, //id: notes.length + 1, }; //console.log("addNote" + newNote); //console.log("addNote", notes); /*const iquals = (newNote, notes) => { return notes.some((note) => note.content === newNote); }; */ //if (iquals(newNote, notes)) { if (notes.some((note) => note.content === newNote)) { //console.log(`${newNote} is already added to phonebook`); alert(`${newNote} is already added to phonebook`); setNewNote(""); } else { //axios.post("http://localhost:3001/notes", noteObject) noteService .create(noteObject) /* .then((response) => { setNotes(notes.concat(response.data)); */ .then((returnedNote) => { setNotes(notes.concat(returnedNote)); setNewNote(""); }); /* setNotes(notes.concat(noteObject)); setNewNote(""); */ //console.log("button clicked", event.target); //console.log(`${newNote} is already added to notes`); } }; /* const handleNoteChange = (event) => { console.log(event.target.value); setNewNote(event.target.value); }; */ /* const handleFilterChange = (event) => { console.log(event.target.value); setFilter(event.target.value); }; */ const filteredNote = notes.filter((item) => item.content.toLowerCase().includes(filter.toLowerCase()) ); const handleFilterChange = (value) => { setFilter(value); }; const notesToShow = showAll ? notes : notes.filter((note) => note.important === true); const toggleImportanceOf = (id) => { //const url = `http://localhost:3001/notes/${id}`; const note = notes.find((n) => n.id === id); const changedNote = { ...note, important: !note.important }; //axios.put(url, changedNote) noteService .update(id, changedNote) /* .then((response) => { setNotes(notes.map((n) => (n.id !== id ? n : response.data))); */ .then((returnedNote) => { setNotes(notes.map((note) => (note.id !== id ? note : returnedNote))); }) .catch((error) => { //alert(`the note '${note.content}' was already deleted from server`); setErrorMessage( `Note '${note.content}' was already removed from server` ) setTimeout(() => { setErrorMessage(null) }, 5000) setNotes(notes.filter((n) => n.id !== id)); }); }; const toggleRemoveOf = (id, content) => { if (window.confirm(`Delete ${content} ?`)) { console.log("si se elimina"); noteService.remove(id).then(data => { setNotes(notes.filter((note) => note.id !== id )); }); } else { //console.log("no se elimina"); //alert("This note dont't have been removed from server"); //window.open("exit.html", "Thanks for Visiting!"); } }; return ( <div> <h1>Notes</h1> <Notification message={errorMessage} /> <h2>Filter by content</h2> <Filter value={filter} onChange={handleFilterChange} /> {/* <div> <input value={filter} onChange={(e) => setFilter(e.target.value)} /> </div> */} <NoteList notes={filteredNote} /> {/* <ul style={{ listStyleType: "none" }}> {filteredNote.map((item) => ( <li style={{ marginBottom: "5px" }} key={item.id}> {item.content} </li> ))} </ul> */} <h2>Show all or important</h2> <ToggleImportant showAll={showAll} setShowAll={setShowAll} /> {/* <div> <button onClick={() => setShowAll(!showAll)}> show {showAll ? "important" : "all"} </button> </div> */} <ul> {notesToShow.map((note) => ( <Note key={note.id} note={note} toggleImportance={() => toggleImportanceOf(note.id)} toggleRemove={() => toggleRemoveOf(note.id, note.content)} /> ))} </ul> <h2>Add a new note</h2> {/* <Add notes={notes} /> */} <form onSubmit={addNote}> <input value={newNote} onChange={(e) => setNewNote(e.target.value)} ref={inputRef} /> <button type="submit">save</button> </form> {/* <div>debug: {newName}</div> */} <Footer /> </div> ); }; export default App;
import hre, { ethers } from "hardhat"; import fs from 'fs'; import { NomoPlayersDropMechanic } from '../typechain'; import { ContractFactory } from 'ethers'; import { addItemsToContract } from '../test/helpers/helpers'; import config from './deployConfig/index'; import dotenv from 'dotenv'; const { coerceUndefined, shuffle } = config; const GAS_LIMIT = '8000000' dotenv.config(); export async function deployNomoPlayersDropMechanic() { await hre.run('compile'); const [deployer] = await hre.ethers.getSigners(); console.log('Deploying contracts with the account:', deployer.address); console.log(`Account balance: ${(await deployer.getBalance()).toString()} \n`); const erc20Address = coerceUndefined(process.env.DAI_ADDRESS); const price = coerceUndefined(process.env.TOKEN_PRICE); const collectionLength = coerceUndefined(process.env.COLLECTION_LENGTH) const maxQuantity = coerceUndefined(process.env.MAX_QUANTITY); const erc721Address = coerceUndefined(process.env.ERC721_ADDRESS); const daoWalletAddress = coerceUndefined(process.env.DAO_WALLET_ADDRESS); const strategyContractAddress = coerceUndefined(process.env.STRATEGY_CONTRACT_ADDRESS); const tokensVault = coerceUndefined(process.env.TOKENS_VAULT); const presaleStartDate = coerceUndefined(process.env.PRESALE_START_DATE); const presaleDuration = coerceUndefined(process.env.PRESALE_DURATION); const vrfCoordinator = coerceUndefined(process.env.VRF_COORDINATOR); const linkToken = coerceUndefined(process.env.LINK_TOKEN); const keyhash = coerceUndefined(process.env.KEYHASH); const fee = coerceUndefined(process.env.FEE); const whitelisted = config.WHITE_LISTED; const privileged = config.PRIVILEGED; const mintedTokens = config.generateCollection(collectionLength); //! shuffled so we do not know the actual order inside const shuffled = shuffle(mintedTokens) const NomoPlayersDropMechanic_Factory: ContractFactory = await hre.ethers.getContractFactory("NomoPlayersDropMechanic"); const nomoPlayersDropMechanicContract = await NomoPlayersDropMechanic_Factory.deploy( erc721Address, tokensVault, price, maxQuantity, vrfCoordinator, linkToken, keyhash, fee, { gasLimit: ethers.BigNumber.from(GAS_LIMIT) }) as NomoPlayersDropMechanic; console.log(`Deploying NomoPlayersDropMechanic at address: ${nomoPlayersDropMechanicContract.address} please wait...\n`); await nomoPlayersDropMechanicContract.deployed() console.log('Setting initial values...\n'); const setErc20tx = await nomoPlayersDropMechanicContract.setERC20Address(erc20Address, { gasLimit: GAS_LIMIT }); await setErc20tx.wait(); console.log(`ERC20 contract has been set at address ${erc20Address}`); const setDAOTx = await nomoPlayersDropMechanicContract.setDaoWalletAddress(daoWalletAddress, { gasLimit: GAS_LIMIT }); await setDAOTx.wait() console.log(`DAO contract has been set at address ${daoWalletAddress}`); const setStrategyTx = await nomoPlayersDropMechanicContract.setStrategyContractAddress(strategyContractAddress, { gasLimit: GAS_LIMIT }); await setStrategyTx.wait(); console.log(`Strategy contract has been set at address ${strategyContractAddress}`); // Set whitelisted addresses await addItemsToContract(whitelisted, nomoPlayersDropMechanicContract.functions["setWhitelisted"], "addresses", false); console.log(`Whitelisted addresses have been set!`); const setPresaleStartTx = await nomoPlayersDropMechanicContract.setPresaleStartDate(presaleStartDate); await setPresaleStartTx.wait() console.log(`Presale start date set on unix: ${presaleStartDate}`); const setPresaleDurationTx = await nomoPlayersDropMechanicContract.setPresaleDuration(presaleDuration); await setPresaleDurationTx.wait(); console.log(`Presale duration has been set to ${presaleDuration} seconds`); // Set tokens await addItemsToContract(shuffled, nomoPlayersDropMechanicContract.functions["addTokensToCollection"], "tokens", false); const setInitialTokensLengthTx = await nomoPlayersDropMechanicContract.setInitialTokensLength(collectionLength) await setInitialTokensLengthTx.wait(); console.log(`Initial tokens length has been set to ${collectionLength}`); // Set privileged addresses await addItemsToContract(privileged, nomoPlayersDropMechanicContract.functions["setPrivileged"], "addresses", false); console.log(`Privileged addresses have been set!`); //! After deploy of the NomoPlayersDropMechanic contract, give approval for all tokens in the ERC721 contract to NomoPlayersDropMechanic contract // await ERC721.setApprovalForAll(nomoPlayersDropMechanicContractAddress, true, { from: tokensVault }); fs.writeFileSync('./contracts.json', JSON.stringify({ network: hre.network.name, nomoPlayersDropMechanic: nomoPlayersDropMechanicContract.address, erc721Address, erc20Address, tokensVault, strategyContractAddress, daoWalletAddress, price, maxQuantity, vrfCoordinator, linkToken, keyhash, fee, collectionLength, presaleStartDate, presaleDuration, mintedTokens: [...shuffled], whitelisted, privileged }, null, 2)); console.log('Done!'); }
import React, { useState, useEffect } from 'react'; import '../../public/sass/index.scss'; import { getAds } from '../api/ads'; import Ad from '../components/ad'; import LoaderWrapper from '../components/loaderWrapper'; import showError from '../toast'; function Home() { const [ads, setAds] = useState([]); const [loading, setLoading] = useState(false); const loadAds = async () => { setLoading(true); try { const res = await getAds(); setAds(res.data); } catch (error) { showError(error); } finally { setLoading(false); } }; useEffect(() => { loadAds(); }, []); const renderAds = () => ads.map((data) => <Ad key={data.id} data={data} />); return ( <div> <div className="advs"> {loading ? <LoaderWrapper /> : renderAds()} </div> <div className="separator" /> </div> ); } export default Home;
#include <stdio.h> #include <stdlib.h> #include <string.h> struct buffer { char data[100]; }; struct message { int type; int pid; struct buffer buffer; }; int main() { FILE *archivo; struct message msg; long int posicion; // Variable para almacenar la posición en el archivo // Abre el archivo en modo lectura archivo = fopen("DonQuijote.txt", "r"); if (archivo == NULL) { perror("Error al abrir el archivo"); return 1; } // Inicializa el buffer en cada mensaje msg.type = 0; msg.pid = 0; memset(msg.buffer.data, 0, sizeof(msg.buffer.data)); // Inicializa el buffer con ceros // Lee el archivo carácter por carácter char caracter; int indice = 0; while ((caracter = fgetc(archivo)) != EOF) { // Si el carácter es un salto de línea, termina la lectura if (caracter == '\n') { break; } // Almacena el carácter en el buffer msg.buffer.data[indice] = caracter; indice++; // Verifica si el buffer se llena if (indice >= sizeof(msg.buffer.data) - 1) { perror("Buffer de línea lleno"); break; } } // Obtiene la posición actual en el archivo posicion = ftell(archivo); //Luego se puede usar fseek para leer apartir de esa posición o desde posicion+1 si hay que saltarse el salto de linea // Imprime la línea leída y la posición en el archivo printf("Línea leída: %s\n", msg.buffer.data); printf("Posición en el archivo: %ld\n", posicion); // Cierra el archivo fclose(archivo); return 0; }
#include<iostream> using namespace std; class Myinterge { friend ostream &operator<<(ostream &cout,Myinterge myint); public: Myinterge() { m_Num = 0; } //前置递增 Myinterge &operator++() { m_Num++; return *this; } //后置递增 Myinterge operator++(int) //int 代表占位参数,可以用于区分前置和后置 { Myinterge temp = *this; m_Num++; return temp; } private: int m_Num; }; //重载左移运算符<<,使得cout可以输出 Myinterge的对象 ostream &operator<<(ostream &cout,Myinterge myint) { cout << myint.m_Num; return cout; } void test() { Myinterge m; cout << m << endl; cout << ++m << endl; cout << ++(++m) << endl; } void test02() { Myinterge m; cout << m++ << endl; cout << m << endl; } int main() { //test(); test02(); return 0; }
from django.conf import settings from django.db import transaction from django.utils import timezone # django 의 time 존을 써야 시간대를 장고의 시간과 맞출 수 있다. from rest_framework.views import APIView from rest_framework.response import Response from .models import Amenity, Room from .serializers import AmenitySerializer, RoomListSerializer, RoomDetailSerializer from rest_framework.exceptions import ( NotFound, NotAuthenticated, ParseError, PermissionDenied, ) from rest_framework.status import HTTP_204_NO_CONTENT, HTTP_200_OK from categories.models import Category from reviews.serializers import ReviewSerializer from medias.serializers import PhotoSerializer from rest_framework.permissions import ( IsAuthenticatedOrReadOnly, ) # GET은 통과, post 는 인증받는사람만 간으하게 해준다. from bookings.models import Booking from bookings.serializers import PublicBookingSerializer,CretaeRoomBookingSerializEr """ /api/v1/rooms/amenities/ /api/v1/rooms/amenities/1 """ class Amenities(APIView): def get(self, request): all_amenities = Amenity.objects.all() serializer = AmenitySerializer(all_amenities, many=True) return Response(serializer.data) def post(self, request): serializer = AmenitySerializer(data=request.data) if serializer.is_valid(): amenity = serializer.save() # 유효하다면 저장하고 보여준다. return Response( AmenitySerializer(amenity).data, ) else: return Response(serializer.errors) class AmenityDetail(APIView): def get_object(self, pk): try: return Amenity.objects.get(pk=pk) except Amenity.DoesNotExist: raise NotFound def get(self, request, pk): # amenity=self.get_object(pk) # serializer=AmenitySerializer(amenity) return Response( AmenitySerializer(self.get_object(pk)).data, ) def put(self, request, pk): amenity = self.get_object(pk) serializer = AmenitySerializer(amenity, data=request.data, partial=True) if serializer.is_valid(): updated_amenity = serializer.save() return Response(AmenitySerializer(updated_amenity).data) else: return Response(serializer.errors) def delete(self, request, pk): amenity = self.get_object(pk) amenity.delete() return Response(status=HTTP_204_NO_CONTENT) class Rooms(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get(self, request): all_rooms = Room.objects.all() serializer = RoomListSerializer( all_rooms, many=True, context={"request": request} ) return Response(serializer.data) def post(self, request): # print(request.user) authenticated 된 유저라면 정보를 받아올 수 있다. serializer = RoomDetailSerializer(data=request.data) if serializer.is_valid(): category_pk = request.data.get("category") if not category_pk: raise ParseError("Category is required.") # 잘못된 데이터 형식을 가지고 있을 때. try: category = Category.objects.get(pk=category_pk) if category == Category.CategoryKindChoices.EXPERIENCES: raise ParseError("the category should be rooms") except Category.DoesNotExist: raise ParseError("category not found") try: with transaction.atomic(): # db에 바로 반영하지 않고, 변경 사항들을 리스트로 만들어서 다 저장되면 DB 로 Push room = serializer.save( owner=request.user, category=category, ) # create 메서드에 **validated_data 에 추가된다. amenities = request.data.get("amenities") for amenity_pk in amenities: amenity = Amenity.objects.get(pk=amenity_pk) room.amenities.add(amenity) serializer = RoomDetailSerializer(room) return Response(serializer.data) except Exception: raise ParseError("Amenity not found") else: return Response(serializer.errors) class RoomDetail(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get_object(self, pk): try: return Room.objects.get(pk=pk) except Room.DoesNotExist: raise NotFound def get(self, request, pk): room = self.get_object(pk) serializer = RoomDetailSerializer(room, context={"request": request}) return Response(serializer.data) def put(self, request, pk): room = self.get_object(pk) if room.owner != request.user: raise PermissionDenied else: serializer = RoomDetailSerializer(room, data=request.data, partial=True) if serializer.is_valid(): updated_room = serializer.save() return Response(RoomDetailSerializer(updated_room).data) else: return Response(serializer.errors) def delete(self, request, pk): room = self.get_object(pk) if room.owner != request.user: raise PermissionDenied else: room.delete() return Response(status=HTTP_204_NO_CONTENT) class RoomReviews(APIView): def get_object(self, pk): try: return Room.objects.get(pk=pk) except Room.DoesNotExist: raise NotFound def get(self, request, pk): try: # print(request.query_params) # 쿼리의 파라미터를 읽어온다. page = request.query_params.get("page", 1) # 없으면 기본값 1. page = int(page) # str 로 가져온다. 또한 정수만 받는다. except ValueError: page = 1 page_size = 3 start = (page - 1) * page_size end = start + page_size room = self.get_object(pk) serializer = ReviewSerializer( room.reviews.all()[start:end], # 쿼리 셋이기 때문에 먼저 가져오게 한다. many=True, ) return Response(serializer.data) class RoomAmenities(APIView): def get_object(self, pk): try: return Room.objects.get(pk=pk) except Room.DoesNotExist: raise NotFound def get(self, request, pk): try: # print(request.query_params) # 쿼리의 파라미터를 읽어온다. page = request.query_params.get("page", 1) # 없으면 기본값 1. page = int(page) # str 로 가져온다. 또한 정수만 받는다. except ValueError: page = 1 page_size = settings.PAGE_SIZE start = (page - 1) * page_size end = start + page_size room = self.get_object(pk) serializer = AmenitySerializer( room.amenities.all()[start:end], # 쿼리 셋이기 때문에 먼저 가져오게 한다. many=True, ) return Response(serializer.data) class RoomPhotos(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get_object(self, pk): try: return Room.objects.get(pk=pk) except Room.DoesNotExist: raise NotFound def post(self, request, pk): room = self.get_object(pk) if request.user != room.owner: raise PermissionDenied serializer = PhotoSerializer(data=request.data) if serializer.is_valid(): photo = serializer.save(room=room) serializer = PhotoSerializer(photo) return Response(serializer.data) else: return Response(serializer.errors) class RoomBookings(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get(self, request, pk): now = timezone.localtime(timezone.now()).date() bookings = Booking.objects.filter( room__pk=pk, kind=Booking.BookingKindChoices.ROOM, checkin__gt=now, ) # DB를 조회하지 않고 booking serializer = PublicBookingSerializer(bookings, many=True) return Response(serializer.data) def post(self,request,pk): room=self.get_object(pk) serializer=CretaeRoomBookingSerializEr(data=request.data) # 체크인, 체크아웃 을 필수로 바구는 시리얼라이저. if serializer.is_valid(): Response ({"ok":True}) else: return Response(serializer.errors)
--- sidebar_position: 2 title: Query NFT holders --- import {Step, Highlight} from '@site/src/lib/utils.mdx' Sends a *REST-API* call to `Loopring` to query NFT holders by `Loopring's` nftData. This function requires input as follows: * URL <Step text="1"/> : The URL to send the request to. * ApiKey <Step text="2"/> : API Key. * NftData <Step text="3"/> : The Loopring's NFT token data identifier which is a hash string of NFT token address and *NFT_ID*. * Offset <Step text="4"/> : Number of records to skip. * Limit <Step text="5"/> : Number of records to return. ![Query NFT holders](_static/img/query-nft-holders.png) The returned *Response* <Step text="6"/> is a struct that holds the response data for the HTTP request sent to `Loopring`. :::note If *Success* is *True* it only means that there was no error on the data transport layer (HTTP). You also need to check the response body to determine the actual outcome of the call. :::
const { AuthenticationError } = require('apollo-server-express') const { User, Ball, Game, Lobby } = require('../models'); const { signToken } = require('../utils/auth'); const resolvers = { Query: { users: async () => { return User.find(); }, multipleUsers: async(parent, { userId }) => { return User.find({ _id: userId }) }, user: async (parent, { userId }) => { // console.log(userId) return User.findOne({ _id: userId}); }, me: async (parent, args, context) => { if (context.user) { return User.findOne({ _id: context.user._id }); } throw new AuthenticationError('You need to be logged in!'); }, lobby: async(parent, { lobbyId }) => { // console.log(lobbyId) return Lobby.findOne({ _id: lobbyId }) }, game: async(parent, { gameId }) => { return Game.findOne({ _id: gameId }) }, }, Mutation: { addUser: async (parent, { email, password, fullname, username }) => { const user = await User.create({ email, password, fullname, username }); const token = signToken(user); return { token, user }; }, login: async (parent, { email, password }) => { const user = await User.findOne({ email }); if (!user) { throw new AuthenticationError('No user with this email found!'); } const correctPw = await user.isCorrectPassword(password); if (!correctPw) { throw new AuthenticationError('Incorrect password!'); } const token = signToken(user); return { token, user }; }, joinLobby: async (parent, { users, lobbyId }) => { return await Lobby.findOneAndUpdate( { _id: lobbyId }, { $addToSet: { users: users }, }, { new: true, runValidators: true, }); }, leaveLobby: async (parent, { users, lobbyId }) => { return await Lobby.findOneAndUpdate( { _id: lobbyId, users: { $elemMatch: { $eq: users } } }, { $pull: { users: users }, }, { new: true, runValidators: true, }); }, joinGame: async (parent, { users, gameId }) => { return await Game.findOneAndUpdate( { _id: gameId }, { $addToSet: { users: users }, }, { new: true, runValidators: true, }, ); }, leaveGame: async (parent, { users, gameId }) => { return await Game.findOneAndUpdate( { _id: gameId, users: { $elemMatch: { $eq: users } } }, { $pull: { users: users }, }, { new: true, runValidators: true, }); }, createLobby: async (parent, { users, gametype }) => { let maxsize = 2; if (gametype == "cutthroat") { maxsize = 5 } return await Lobby.create({ users, gametype, maxsize }) }, // inLobby: async(parent, { some, thing }) => { // let lobbyCount = 0; // if (gametype == "cutthroat") { // if (lobbyCount == 3 || lobbyCount == 5) { // return Lobby.create({ users, gametype }) // } // } else { // return "Cannot start game" // } // } createGame: async(parent, { users, gametype }) => { const ballCount = 16; const balls = []; let numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] let index = 0; let cutThroatRandomize = false let userCount = users.length let ballValue = numArr[index] let assignedUserId = 0 let assignedUserIndex = 0 if (gametype == 'nineball') { ballCount = 10; numArr.slice(9) console.log("Nineball Array: " + numArr) } let ballsPerUser = ballCount/userCount if (gametype == 'cutthroat') { cutThroatRandomize = true } let iterations = 0 while (numArr.length !== 0) { let type; if (cutThroatRandomize) { index = Math.floor(Math.random() * numArr.length) if (iterations % ballsPerUser == 0) { let assignedUser = await User.findById(users[assignedUserIndex])// assumes users at assignedUserIndex is being passed in as the id of the user assignedUserId = assignedUser._id assignedUserIndex += 1 } } if (ballValue > 8 && ballValue <= 15) { type = "stripe" } else if (ballValue == 8) { type = "solid" // can change if desired in the future 8 ball } else { type = "solid" } ballValue = numArr[index] balls.push({ number: ballValue, type: type, status: false, assigneduser: assignedUserId}); numArr.splice(index, 1) iterations++ } // if want to detect cue ball getting scratched, push cue ball here // if (trackCue) { // balls.push({number: 16, type: "Cue", status: false, assigneduser: null}) // } let game = await Game.create({ users, balls, gametype }) return game } }, }; module.exports = resolvers;
screenplay = {} screenplay.chains = {} -- store built screenplay objects. screenplay.chains.quest = {} screenplay.pause_camera = false -- stop camera lock features when needed. screenplay.__index = screenplay function screenplay:new() local o = {} setmetatable(o, self) return o end function screenplay:run(chain) utils.debugfunc(function() speak:startscene(chain) end, "screenplay:run") end function screenplay:build() -- quest lineage id builder: local id = 0 local idf = function() id = id + 1 return id end -- uses pre-placed units (will break if they are deleted). actor_worker = speak.actor:new() actor_worker:assign(udg_actors[1], { none = 'war3mapImported\\portrait_worker.blp' }) actor_shinykeeper = speak.actor:new() actor_shinykeeper:assign(udg_actors[2], { none = 'war3mapImported\\portrait_blacksmith.blp' }) actor_digmaster = speak.actor:new() actor_digmaster:assign(udg_actors[3], { none = 'war3mapImported\\portrait_taskmaster.blp' }) actor_elementalist = speak.actor:new() actor_elementalist:assign(udg_actors[4], { none = 'war3mapImported\\portrait_gemhoarder.blp' }) actor_narrator = speak.actor:new() actor_narrator:assign(udg_actors[5], { none = 'war3mapImported\\portrait_narrator.blp' }) actor_grog = speak.actor:new() actor_grog:assign(udg_actors[6], { none = 'war3mapImported\\portrait_grog.blp' }) actor_slog = speak.actor:new() actor_slog:assign(udg_actors[7], { none = 'war3mapImported\\portrait_slog.blp' }) actor_greywhisker = speak.actor:new() actor_greywhisker:assign(udg_actors[8], { none = 'war3mapImported\\portrait_greywhisker.blp' }) --[[ *************************************************************************** ******************************* screenplays ******************************* *************************************************************************** item format: { text, actor [, emotion, anim, sound, func] } --]] screenplay.chains.narrator_intro = speak.chain:build({ [1] = {"...", actor_narrator}, [2] = {"Oh, I didn't see you there.", actor_narrator}, [3] = {"Very well, no need for long introductions. Let's get you on your journey, shall we? I sense your hunger for adventure and treasure.", actor_narrator}, [4] = {"This is the cave of the Tunnel Rat Clan.", actor_narrator}, [5] = {"They've seen... better times. Can you help them reclaim their glory in the depths?", actor_narrator}, [6] = {"Well, what are we waiting for?", actor_narrator}, [7] = {"Use the |c0000f066D|r key to speak to characters in the world. Try it on the kobold marked by a yellow |c0000f066'!'|r.", actor_narrator}, [8] = {"If you ever miss a piece of dialogue or want to re-read it, try the Message Log (|c0000f066F12|r).", actor_narrator}, }) screenplay.chains.narrator_intro_freeplay = speak.chain:build({ [1] = {"Welcome to |c0000f066free play|r mode.", actor_narrator}, [2] = {"This is intended for players who have completed the story, or for those who don't care for it in the first place.", actor_narrator}, [3] = {"In this mode, no story quests are available, and |c00ff3e3esaving is disabled|r.", actor_narrator}, [4] = {"Instead, you start at |c0000f066level 45|r with items and a stash of ore and gold.", actor_narrator}, [5] = {"Additionally, the speed of leveling is greatly accelerated.", actor_narrator}, [6] = {"Explore, run missions, and fight bosses at your leisure. Have fun!", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The kobold jumps, not noticing you walk up behind him. How rude.", actor_narrator}, [2] = {"Scrat scrat! Welcome to depths, greenwhisker.", actor_worker}, [3] = {"Why you come? You here for treasure? We have no treasure.", actor_worker}, [4] = {"Big boyos in tunnels keep miners away. Come from old chambers sometimes. Take kobolds. Kobolds never return.", actor_worker}, [5] = {"The kobold examines your torn pants, missing shirt, and mostly-melted candle. And your complete lack of treasure.", actor_narrator}, [6] = {"Ah, you loser like me!", actor_worker}, [7] = {"The kobold bursts into laughter, nearly falling to the floor. Before long, his face freezes as his eyes meet your gaze.", actor_narrator}, [8] = {"Ah, but you different. It clear. You determined, why else you come all the way down?", actor_worker}, [9] = {"I sense Koboltagonist! I see it! Prophecy? Koboltagonist return to save us? Could be? Is! Is be!", actor_worker}, [10] = {"You look at the kobold with peculiar eyes as he babbles incoherently, but it does not deter his excitement.", actor_narrator}, [11] = {"Yes, yes, you save us from big boyos! But, but...", actor_worker}, [12] = {"...but first, see Shinykeeper. Shinykeeper have shinies for you. Your dull shinies no good for Koboltagonist.", actor_worker}, [13] = {"Now go! For Kingdom! Rock and stone, to the bo- err, wrong game. Ahem.", actor_worker}, [14] = {"...", actor_worker}, [15] = {"I can't come up with phrase, I give up. Okay, you go now! Scrat!", actor_worker}, [16] = {"Well, that was fast. The Shinykeeper is just south of you. By the piles of junk.", actor_narrator}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"Strange tinkering noises can be heard as the Shinykeeper rummages through a bag of what is obviously junk.", actor_narrator}, [2] = {"...", actor_shinykeeper}, [3] = {"Baah!", actor_shinykeeper}, [4] = {"Me no see you there!", actor_shinykeeper}, [5] = {"What you want?", actor_shinykeeper}, [6] = {"...", actor_shinykeeper}, [7] = {"Oh, I see. The silent Kolbotagonist type. See what I do there? I break fourth tunnel.", actor_shinykeeper}, [8] = {"...", actor_shinykeeper}, [9] = {"Shinies? I see in your eye. Scrat! Okay, you have some of my shinies, but not all!", actor_shinykeeper}, [10] = {"With reluctance to let go, the Shinykeeper gives you a handful of junk.", actor_narrator}, [11] = {"Wha? You no like? You wear on head, see!", actor_shinykeeper}, [12] = {"The Shinykeeper puts a bucket on his head and lights a pile of dirty wax to demonstrate his mastery, then places it on your head.", actor_narrator}, [13] = {"The follow-up grin is too wide for any sane kobold.", actor_narrator}, [14] = {"See! Shiny fit perfect. Okay, now you go! Dig Master waiting.", actor_shinykeeper}, [15] = {"Don't forget to equip your... new junk. The equipment and inventory pages can be opened with the |c0000f066V|r and |c0000f066B|r keys respectively.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Dig Master notices your presence, but continues to stare at what resembles a paper map of tunnels.", actor_narrator}, [2] = {"You casually point out to him that the map is upside down.", actor_narrator}, [3] = {"...", actor_digmaster}, [4] = {"Bagh!? A greenwhisker know best, aye?", actor_digmaster}, [5] = {"What appears as anger suddenly fades as The Dig Master bursts out in laughter.", actor_narrator}, [6] = {"By dirt, no one talk like that in long time. You okay to me, greenwhisker. You tough to authority. Definitely Koboltagonist.", actor_digmaster}, [7] = {"We save HARDEST missions for Koboltagonist. You prove worth, okay?", actor_digmaster}, [9] = {"The Dig Master points to his now-correctly-oriented map.", actor_narrator}, [10] = {"Here, you go here. Many shinies left by miners long ago.", actor_digmaster}, [11] = {"You careful though, greenie. There two strong guardians!", actor_digmaster}, [12] = {"You defeat them, yes? Gather shinies? No come back with shinies means no come back at all!", actor_digmaster}, [13] = {"Well, what you wait for? Go fetch shinies!", actor_digmaster}, [14] = {"The Dig Master has given you a quest to complete a dig in a random biome.", actor_narrator}, [15] = {"Use the |c0000f066Tab|r key to open the dig map, or select it with its icon in the lower right. All main interface pages have a menu button there.", actor_narrator}, [16] = {"Inside a dig, your candle light will dwindle over time. The powers of The Darkness will be attracted to you as it fades.", actor_narrator}, [17] = {"|c00fdff6fWax Canisters|r can be acquired within digs from certain creatures or events to replenish your wax capacity.", actor_narrator}, [18] = {"Now, get going. And good luck! Oh, almost forgot. If your candle light goes out |c00ff3e3eThe Darkness|r itself will hunt you. No pressure!", actor_narrator}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The Dig Master looks confused while flipping his map around in random directions.", actor_narrator}, [2] = {"Greenwhisker! You back, by dirt!", actor_digmaster}, [3] = {"Little faith, but here you! Good, good.", actor_digmaster}, [4] = {"You shuffle through your treasure bag and pull out a recovered item.", actor_narrator}, [5] = {"...", actor_digmaster}, [6] = {"What this? This is junk!", actor_digmaster}, [7] = {"The Dig Master twirls the piece in his hand rapidly while examining it.", actor_narrator}, [8] = {"But, you new and green. We do better next time, yea?", actor_digmaster}, [9] = {"He quickly pockets the junk.", actor_narrator}, [10] = {"Now, go see Shinykeeper. They have new task for you.", actor_digmaster}, [11] = {"You've leveled up after finishing a dig and this quest!", actor_narrator}, [12] = {"If you haven't done so already, browse the new items acquired from your successful dig and see if they're worthy of a 'Koboltagonist'.", actor_narrator}, [13] = {"You should also have character attribute and mastery points available to spend.", actor_narrator}, [14] = {"To begin spending, open the character page with the |c0000f066C|r key, and the mastery page with the |c0000f066N|r key.", actor_narrator}, [15] = {"Use character attributes to boost certain stats. Mastery points offer similar benefits, but can ultimately unlock new abilities deeper in.", actor_narrator}, [16] = {"Spend your earned points wisely, as they are non-refundable!", actor_narrator}, [17] = {"Oh, and one last thing, promise.", actor_narrator}, [18] = {"Abilities unlock every 3 levels. You should have a new one unlocked now. See what it is in your skillbook, which opens with the |c0000f066K|r key.", actor_narrator}, [19] = {"If that was too much, here's a tip: whenever you earn new things, a green alert icon will appear over the menu button in the lower right.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Shinykeeper appears distraught, running around frantically.", actor_narrator}, [2] = {"Scrat! It gone! Scrat, it gone for good!", actor_shinykeeper}, [3] = {"...", actor_shinykeeper}, [4] = {"Ah, Koboltagonist! You help, yes? Like you help Dig Master.", actor_shinykeeper}, [5] = {"My hammer, it is taken. Taken by filthy tunnel vermin on last dig.", actor_shinykeeper}, [6] = {"Without hammer, cannot make shinies! See...", actor_shinykeeper}, [7] = {"The Shinykeeper attempts to bash a nail in with the tip of an old boot. Kobolds seem to have an affection for shoes.", actor_narrator}, [8] = {"...see, you see! No good!", actor_shinykeeper}, [9] = {"What say you? You hunt bests? Slay them! Return hammer?", actor_shinykeeper}, [10] = {"Yes, yes. You do that, we make and trade shinies!", actor_shinykeeper}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The Shinykeeper stops removing nails from his boot and looks up to greet you.", actor_narrator}, [2] = {"...", actor_shinykeeper}, [3] = {"How? We thought you dead for good! We thought you turn to slag. But... is that...", actor_shinykeeper}, [4] = {"The hammer disappears from your hands before you can extend it outward.", actor_narrator}, [5] = {"...now! Now we in business!", actor_shinykeeper}, [6] = {"He dances around like a maniac.", actor_narrator}, [7] = {"...", actor_shinykeeper}, [8] = {"Ah yes. Yes, yes! You need any shinies, you see me. Okay, Kolbotagonist?", actor_shinykeeper}, [9] = {"They not powerful. Not yet. Still need more tools. But for now, fill missing shoe? Missing bucket? Scrat! Anything!", actor_shinykeeper}, [10] = {"You now have access to the Shinykeeper's shop outside of digs. Open it by clicking his icon near your skill bar.", actor_narrator}, [11] = {"At this new shop, you can turn your earned gold into items with random features.", actor_narrator}, [12] = {"I suspect the hammer was not the only thing missing. We'll find out soon enough.", actor_narrator}, [13] = {"Well, this is great progress thus far, Koboltagonist. And you haven't event died yet! Surely by now-", actor_narrator}, [14] = {"...well, anyways. The Elementalist was making strange poses earlier. Shall you, ahem, get moving?", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"Oh, so that's how it will be!?", actor_elementalist}, [2] = {"You?! You! Why you...!", actor_elementalist}, [3] = {"...", actor_elementalist}, [4] = {"The kobold wizard points a finger at a rock while holding up a shoe.", actor_narrator}, [5] = {"By the power of STONE, I transmute and convert thee!", actor_elementalist}, [6] = {"...", actor_elementalist}, [7] = {"Nothing happens.", actor_narrator}, [8] = {"Blast, no good stones! Not again!", actor_elementalist}, [9] = {"The Elementalist turns to you, now pointing his finger at your nose.", actor_narrator}, [10] = {"Kolbotagonist, I can sense it. The rocks speak, and do not lie. They tell of the shinies you bring for the Dig Master.", actor_elementalist}, [11] = {"We need different shinies. We need magical shinies. Can you bring?", actor_elementalist}, [12] = {"Bring me shinies and I will show you the true power of geomancy!", actor_elementalist}, [13] = {"The Elementalist resumes his incantation, this time holding a spoon.", actor_narrator}, [14] = {"You'd best be off, before something terrible happens.", actor_narrator}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"You step over a bent spoon.", actor_narrator}, [2] = {"Ah! Koboltagonist! You bring good stone?", actor_elementalist}, [3] = {"...", actor_elementalist}, [4] = {"The Elementalist takes an imbued rock from your outstretched hand.", actor_narrator}, [5] = {"Good.. good! Glow wax will do wonders on this specimen.", actor_elementalist}, [6] = {"The Elementalist waves his arms around like a lunatic while chanting 'bobbity shmobbity' at his shoe.", actor_narrator}, [7] = {"The Elementalist lowers his hands in disappointment before trying once more.", actor_narrator}, [8] = {"By shroom and fungus! Glow wax too viscose? Candle calibration low? Hand waving not fas-", actor_elementalist}, [9] = {"The shoe bursts in a glow of light, sending the Elementalist back over a table.", actor_narrator}, [10] = {"He peers over the table with a coal-black face save for his two beady eyes.", actor_narrator}, [11] = {"Ahah!", actor_elementalist}, [12] = {"He picks up his shoe from across the cave floor, dancing around in celebration.", actor_narrator}, [13] = {"Today, you do good. You now no longer a greenwhisker, greenwhisker. You ever need magic shoe, you come to me.", actor_elementalist}, [14] = {"Oh, almost forget! Here, you have some stones. We don't need all.", actor_elementalist}, [15] = {"The Elementalist hands you 10 pieces of magical ore. You guessed it right: it's a freebie to test out his new fancy shop.", actor_narrator}, [16] = {"You can |c0000f066craft|r new items at the Elementalist with ore mined on digs. Keep track of your ore count your inventory (|c0000f066B|r).", actor_narrator}, [17] = {"Click his head icon near the center of your skillbar to start making new 'shinies', as they say.", actor_narrator}, [18] = {"Crafting an elemental item will yield a guaranteed damage modifier matching the chosen ore's element type.", actor_narrator}, [19] = {"Additionally, the Elementalist's items will roll slightly higher stats than the Shinykeeper. Less... hammering, is involved.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"Koboltagonist!", actor_digmaster}, [2] = {"The Dig Master flips his map around in circles as a fellow kobold scout leaves the table.", actor_narrator}, [3] = {"He steps from his mount and slams the paper on the table.", actor_narrator}, [4] = {"Perfect solution. No fooling. Master plan. Look here.", actor_digmaster}, [5] = {"He points to an assortment of illegible scribbles on his map.", actor_narrator}, [6] = {"...", actor_digmaster}, [7] = {"What? No see?", actor_digmaster}, [8] = {"New tunnel! Or, chamber. Big chamber. But, kept shut by old machine. Requires key.", actor_digmaster}, [9] = {"Elementalist say we need ancient stones to open.", actor_digmaster}, [10] = {"Could be room we heard of long ago.", actor_digmaster}, [11] = {"Uncertain. Risky. But BIG shiny worth all risk! But, for getting ancient stones...", actor_digmaster}, [12] = {"He looks at you and grins.", actor_narrator}, [13] = {"In luck. Elementalist say Greywhisker have stones, stashed away for many winters. He once a Geomancer. Knows ancient magic. Sadly, years numbered.", actor_digmaster}, [14] = {"Here, take to Greywhisker and trade for stones. Ask to use old magic to make key. Perfect trade. No better trade.", actor_digmaster}, [15] = {"He places a giant block of cheese in your hands. A sheet of paper featuring a drawing of a strange jewel is nailed to its top.", actor_narrator}, [16] = {"You look at The Dig Master with a raised brow, your lip half-agape.", actor_narrator}, [17] = {"Well? Why wait? Go get stones! Get key!", actor_digmaster}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The Greywhisker twists his roast on the fire, not looking up as you approach.", actor_narrator}, [2] = {"You step forward, extending your two open hands with the giant chunk of cheese.", actor_narrator}, [3] = {"The Greywhisker's face does not budge. After a pause, his nose fidgets in your direction with a burst of sniffs.", actor_narrator}, [4] = {"With a sudden clang of metal and stone, he lunges over loose stones and empty pots to stand in front of you.", actor_narrator}, [5] = {"He holds an old cane with twirling designs before meeting a broken tip where a jewel might've been, where he rests a shaking hand.", actor_narrator}, [6] = {"He grunts.", actor_narrator}, [7] = {"You grunt.", actor_narrator}, [8] = {"He grunts again, louder.", actor_narrator}, [9] = {"You raise your hands a little higher.", actor_narrator}, [10] = {"The old kobold uses the tip of his staff to unfold the paper stuck to the block.", actor_narrator}, [11] = {"His white eyes study the paper for a long while. They dart to you occasionally, measuring your attire and pickaxe.", actor_narrator}, [12] = {"In another—surprisingly hasty—dash, he goes to his tent and disappears.", actor_narrator}, [13] = {"There's a clattering of boxes and unfurled bags before he emerges again. He approaches you with a small satchel.", actor_narrator}, [14] = {"From the bag, he pulls a series of glowing stones, each a different color. With precision, he slams a prismatic specimen into his staff.", actor_narrator}, [15] = {"To your amazement, the old kobold manages to let a grin slip.", actor_narrator}, [16] = {"His arm bolts to his his beard of whiskers, rummaging about.", actor_narrator}, [17] = {"From it, he pulls a strange looking slab. It glows orange and emits a strange hum.", actor_narrator}, [18] = {"In the blink of an eye, his hand snatches the chunk of cheese from your hand, leaving the glowing fragment in its place.", actor_narrator}, [19] = {"He grunts a final time before returning to the fire, cutting at the cheese with a broken dagger and placing it atop his roast.", actor_narrator}, [20] = {"When you are ready, young one, come see me. I know this blueprint, from long ago.", actor_greywhisker}, [21] = {"His hand moves to a blackened scar on forearm. His fingers rub at its rough edges.", actor_narrator}, [22] = {"I will make the keys you seek. But, be warned: there is only doom on the other side of the lost chambers. Come to me when you are ready.", actor_greywhisker}, [23] = {"You can now craft |c0047c9ffDig Site Keys|r in exchange for |c00ff9c00Ancient Fragments|r at the Greywhisker.", actor_narrator}, [24] = {"A new icon in the middle of your skillbar allows for easy access. |c00ff9c00Ancient Fragments|r are acquired from certain shrines found within digs.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"See, Koboltagonist! Easy.", actor_digmaster}, [2] = {"Cheese never fail.", actor_digmaster}, [3] = {"Now, take new key and open vault.", actor_digmaster}, [4] = {"...", actor_digmaster}, [5] = {"Okay fine. Risk mean reward. We pay you, too. Koboltagonist need gold, too, aye?", actor_digmaster}, [6] = {"Gold and treasure! Yeehehehe-hoo!", actor_digmaster}, [7] = {"...", actor_digmaster}, [8] = {"Okay, go. Best only be you, how else you remain Koboltagonist? Kingdom fall for good without Dig Master.", actor_digmaster}, [9] = {"He smiles to reveal staggered golden teeth.", actor_narrator}, [10] = {"No problem, promise. Easy job! What worst that can happen?", actor_digmaster}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The sheen of the Slag King's Relic glows bright in the wonderous eyes of the Dig Master.", actor_narrator}, [2] = {"...you... you...", actor_digmaster}, [3] = {"...you did it! By dirt! The Koboltagonist did it! Knew Koboltagonist was Koboltagonist, knew it!", actor_digmaster}, [4] = {"He takes the relic and flails about excitedly before placing it on a giant pedastal.", actor_narrator}, [5] = {"There are several empty pedastals nearby. Your eye pans across them before meeting the Dig Master, who looks at you with a keen brow.", actor_narrator}, [6] = {"Koboltagonist, I see your gaze. You are smart one. Observing. Calculating.", actor_digmaster}, [7] = {"True, this not the last relic to seek.", actor_digmaster}, [8] = {"He places his map on the table. With careful hands, he peels the top of it away to reveal a hidden outline underneath.", actor_narrator}, [9] = {"The new map features a series of colored diamonds: orange, green, red and blue. They each connect via odd shapes to its center, " .."which is marked by a red 'X'", actor_narrator}, [10] = {"We get all four, from lost chambers. We unlock secret deep within tunnel, far below. Ancient vault. Treasure-filled.", actor_digmaster}, [11] = {"He says the words while shifting a silver chain between his fingers. He then grips it and stands straight.", actor_narrator}, [12] = {"You give a concerned shake of your head.", actor_narrator}, [13] = {"Wha'? Always treasure in center of odd maps and strange doors! Puzzle, aye? What else?", actor_digmaster}, [14] = {"We do this, Koboltagonist, for Kingdom. Must. Necessary. Required.", actor_digmaster}, [15] = {"His confident facade quickly fades and he collapses his shoulders.", actor_narrator}, [16] = {"Scrat! No... Fine! You right. I don't know how to find others. But you, Koboltagonist, have makings of Goldwhisker. Tales for next hundred years!", actor_digmaster}, [17] = {"That why you here, no? But first, see Shinykeeper. To fight more big boyos, need more shinies.", actor_digmaster}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Shinykeeper flips through a book while scratching his head. He notices you, placing the book upright on his workbench.", actor_narrator}, [2] = {"It falls open, revealing empty pages.", actor_narrator}, [3] = {"Kolbotagonist, we got problem. See book? You see?", actor_shinykeeper}, [4] = {"He holds the book up. The empty pages fall out and scatter about the floor.", actor_narrator}, [5] = {"No good... no good at all! How can we have shinies with book with no scribbles?", actor_shinykeeper}, [6] = {"You look at him oddly.", actor_narrator}, [7] = {"What? I scribble? I can't! Don't know how. Can only swing HAMMER!", actor_shinykeeper}, [8] = {"The Shinykeeper holds his hammer outward in a daring pose.", actor_narrator}, [9] = {"Now, you go! Get shiny book! Then we make all the shinies!", actor_shinykeeper}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"Ah! You got scribbles!", actor_shinykeeper}, [2] = {"The Shinykeeper snatches the book from your hands and jumps to a page with expert precision.", actor_narrator}, [3] = {"His eyes dart around, observing the details of... another blank page.", actor_narrator}, [4] = {"You look at him confusedly. He shuts the book and grabs his hammer.", actor_narrator}, [5] = {"Tweak the gizmo, slam the doohickey, polish the dinger!", actor_shinykeeper}, [6] = {"Despite the chaotic display, the Shinykeeper emerges with a fancy slab that actually resembles boots.", actor_narrator}, [7] = {"Here, for you, Koboltagonist. And much more coming! You bring gold, I make shinies. Many shinies! UNLIMITED shinies!", actor_shinykeeper}, [8] = {"He returns to his workbench and raises his hammer, only to realize the table is now empty of supplies.", actor_narrator}, [9] = {"Hehe... scrat. Koboltagonist. You got... gold, yes?", actor_shinykeeper}, [10] = {"You have unlocked |c0000f066improved crafting|r at the Shinykeeper.", actor_narrator}, [11] = {"Items sold by the Shinykeeper will roll with an additional stat, and have a chance to roll secondary attributes.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Elementalist places his latest pair of boots on a carefully arranged pile of other enchanted boots.", actor_narrator}, [2] = {"He stands still for a moment, observing his collection triumphantly with both hands at his hips.", actor_narrator}, [3] = {"Koboltagonist! Timing always perfect, always where needed. Like true Koboltagonist. I have task.", actor_elementalist}, [4] = {"Magic stones are very nice. Yes, very nice, indeed. But, something missing. Not quite right.", actor_elementalist}, [5] = {"He rubs his brow with one hand while pacing slowly. You suspect he might hurt himself in intense thought before he jumps upright.", actor_narrator}, [6] = {"By all that is gold! Of course...", actor_elementalist}, [7] = {"...we missing crystals. Can't have shiniest of shinies with no crystals. Clear rock complement solid rock, yea?", actor_elementalist}, [8] = {"You squint at the suggestion, but he continues before you can interject.", actor_narrator}, [9] = {"You find for me? Crystals help make newer shinies to defeat big boyos.", actor_elementalist}, [10] = {"The Elementalist returns to his collection. A pair of boots slips slightly, which he instantly fixes with a quick gesture and nod.", actor_narrator}, [11] = {"He's clearly... busy. Best we be off.", actor_narrator}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"You slam the crystalline gizmo on the ground in front of the Elementalist.", actor_narrator}, [2] = {"He screeches and jumps back in surprise, hiding behind a stack of debris.", actor_narrator}, [3] = {"He hastily pokes his nose out from the pile of stone, sniffing intensely.", actor_narrator}, [4] = {"My nose... it never lies... could it be...", actor_elementalist}, [5] = {"The Elementalist bolts from behind the rubble, clattering his fingers over the crystal object with intense interest.", actor_narrator}, [6] = {"...pure crystal! Strong infusion, high longevity, minimal energy input required. Maximal output guaranteed.", actor_elementalist}, [7] = {"...", actor_elementalist}, [8] = {"But... red?! Why always red?! Needed clear!", actor_elementalist}, [9] = {"No, no matter. Red will do. Reverse arcane energy stream, fortify amplification process, borrow Shinykeeper hammer. He won't mind.", actor_elementalist}, [10] = {"We begin immediately!", actor_elementalist}, [11] = {"The Elementalist hands you a pile of magical ore.", actor_narrator}, [12] = {"You have unlocked |c0000f066improved crafting|r at the Elementalist.", actor_narrator}, [13] = {"Items crafted by the Elementalist will now roll secondary attributes.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"Koboltagonist, news of next chamber! Thanks to Shinykeeper's new book.", actor_digmaster}, [2] = {"The glimpse of empty pages enters your mind. You decide not to dwell on the Shinykeeper's methods. It's probably for the best.", actor_narrator}, [3] = {"Tales speak of big creature in Mire, deep within. Lurking.", actor_digmaster}, [4] = {"Big fish boyo ate adventurer carrying ancient relic...", actor_digmaster}, [5] = {"The Dig Master rubs his belly while grinning.", actor_narrator}, [6] = {"...understand? Of course you understand! You Koboltagonist! You expert! Probably done many times before.", actor_digmaster}, [7] = {"...", actor_digmaster}, [8] = {"Ahem. So, you slay big beastie? Second relic means halfway to vault!", actor_digmaster}, [9] = {"Me? I go? No... no, can't go. See?", actor_digmaster}, [10] = {"He raises his leg, which is wrapped in a bandage, and points with a frown.", actor_narrator}, [11] = {"The Dig Master places it down without effort. You notice an apparent delay before he forces a wince out and clutches it dramatically.", actor_narrator}, [12] = {"He grins with assumed innocence.", actor_narrator}, [13] = {"You look on, unconvinced.", actor_narrator}, [14] = {"*Sigh*... Koboltagonist, I be straight. I too old. Hard to admit, but can barely ride rat for much longer. Greywhisker years approaching.", actor_digmaster}, [15] = {"And Elementalist, he too blind. Shinykeeper? Too cowardly, like most scouts.", actor_digmaster}, [16] = {"But you? You so brave it almost stupid! Already have one relic, what's one more?", actor_digmaster}, [17] = {"What you say?", actor_digmaster}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The Dig Master notices you approaching and quickly resumes a limping position.", actor_narrator}, [2] = {"You pull the ancient relic from your backpack and place it on the ground. It's fresh with slime.", actor_narrator}, [3] = {"Ugh! Smells!", actor_digmaster}, [4] = {"...", actor_digmaster}, [5] = {"But... so... shiny!", actor_digmaster}, [6] = {"The Dig Master grabs the relic, ripping the bandage from his leg and wiping it clean.", actor_narrator}, [7] = {"He stops, grinning nervously with the relic held above.", actor_narrator}, [8] = {"Ah, such shinies. Make leg better. Hehe...", actor_digmaster}, [9] = {"The Dig Master places the relic on an empty pedastal. It seems to glow slightly brighter when paired with the first.", actor_narrator}, [10] = {"So much closer to vault, Koboltagonist!", actor_digmaster}, [11] = {"Unclear where next relic. I keep eye to ground, yea? Doh! I mean ear! Yes, ear. Or, eye? No, both!", actor_digmaster}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Shinykeeper studies his hammer intently as you approach.", actor_narrator}, [2] = {"Koboltagonist, proposition for you.", actor_shinykeeper}, [3] = {"You like shinies, ya?", actor_shinykeeper}, [4] = {"You nod.", actor_narrator}, [5] = {"You like shinies that are more shiny than other shinies, ya?", actor_shinykeeper}, [6] = {"You nod again.", actor_narrator}, [7] = {"The Shinykeeper pulls out his 'scribbles' and looks over a page.", actor_narrator}, [8] = {"It's another empty page. As you tilt your head sideways in typical, confused fashion, he slams the book shut.", actor_narrator}, [9] = {"Design, I have. To make best of all shinies. But, big order coming up for Dig Master. Can't venture to acquire.", actor_shinykeeper}, [10] = {"Requires research. Requires plans. Have plenty of research, but missing blueprint.", actor_shinykeeper}, [10] = {"He doesn't say anything else. Instead, he looks at you in expected, measured silence.", actor_narrator}, [11] = {"...", actor_shinykeeper}, [12] = {"You grab your pickaxe and shoulder it. The Shinykeeper gives a familiar, whacky grin, then returns to hammering at a pile of junk.", actor_narrator}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"You place the discovered 'blueprint' on the Shinykeeper's workbench.", actor_narrator}, [2] = {"He unfurls the document, only to be met with... an empty sheet of paper.", actor_narrator}, [3] = {"Sensing disappointment in the silent stare, you turn to leave...", actor_narrator}, [4] = {"...OF COURSE!", actor_shinykeeper}, [5] = {"He rips the blank blueprint from the table and pins it to a drawing board.", actor_narrator}, [6] = {"The Shinykeeper darts around his workshop, sifting through planks, bolts, cans, shoes, rods and pots.", actor_narrator}, [7] = {"Around you turns to dust in the frenzy, with only the sound of clattering metal and a banging hammer.", actor_narrator}, [8] = {"As the dust settles, the shape of a strange device can be made out in the corner of the room.", actor_narrator}, [9] = {"Test, shall we? Yes, test! What you need... what useful. Hmm. Potions? Artifacts? No problem!", actor_shinykeeper}, [10] = {"He throws a concoction of random junk into the machine, twists dials, turns knobs, inserts gold coins, then pulls a lever.", actor_narrator}, [11] = {"The device roars to life, churning internally with crunching vibrations. As it comes to a halt, two thuds can be heard.", actor_narrator}, [12] = {"Well, what you think? SUPER SHINY!", actor_shinykeeper}, [13] = {"He hands you the two pieces of... well, they're not actually junk anymore. You raise your eyebrows, then nod slowly with satisfaction.", actor_narrator}, [14] = {"Can't always get shinier shinies, but what fun if always shiny?", actor_shinykeeper}, [15] = {"You have unlocked |c0000f066improved crafting|r at the Shinykeeper.", actor_narrator}, [16] = {"Items crafted by the Shinykeeper now have a chance to be |c00c445ffEpic|r in quality.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Elementalist stares blankly into the infusion crystal.", actor_narrator}, [2] = {"You begin to move forward, but a loud crackle sends the Elementalist flying.", actor_narrator}, [3] = {"He picks himself up and dusts off the black coal front his pant legs.", actor_narrator}, [4] = {"New problem, Koboltagonist. Trying to make better shinies, but crystal not giving in. Overworked. Oversaturated.", actor_elementalist}, [5] = {"Solution, I have.", actor_elementalist}, [6] = {"More crystal! Only way. Twice the crystal, twice the work.", actor_elementalist}, [7] = {"Bring new one, and I show you what is possible.", actor_elementalist}, [8] = {"...", actor_elementalist}, [9] = {"Oh, and not red! Anything but red.", actor_elementalist}, [10] = {"He resumes his incantation in the reflection of the crystalline mirror.", actor_narrator}, [11] = {"You notice singed hairs atop his head, but decide to leave him be as he begins to mumble strange sounds.", actor_narrator}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The Elementalist removes the crystal from your hands.", actor_narrator}, [2] = {"Bah! Red again!", actor_elementalist}, [3] = {"He looks at you with contempt for a moment before noticing your torn pants, half-melted candle, and bruised arms.", actor_narrator}, [4] = {"Ah, Koboltagonist, forgive. Hard to get. Whining too much. Why strange mage always the one to whine?", actor_elementalist}, [5] = {"Red will do. Stand back.", actor_elementalist}, [6] = {"...", actor_elementalist}, [7] = {"He places the crystal on its new podium and begins a new incantation.", actor_narrator}, [8] = {"You listen intently, placing your backpack on a nearby table and taking a step back, twice as far this time).", actor_narrator}, [9] = {"Before you can object, the Elementalist grabs your backpack from the table.", actor_narrator}, [10] = {"A plume of smoke erupts from the crystal, followed by purple lights.", actor_narrator}, [11] = {"I command thee, backpack, to take on the power of... EPICNESS!", actor_elementalist}, [12] = {"The area clears, and the Elementalist emerges, covered head to toe in black soot.", actor_narrator}, [13] = {"You see! Easy! Can't guarantee every time. But, some of the time: EPICNESS.", actor_elementalist}, [14] = {"You have unlocked |c0000f066improved crafting|r at the Elementalist.", actor_narrator}, [15] = {"Items crafted by the Elementalist now have a chance to be |c00c445ffEpic|r in quality.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Dig Master stands between the two relics. Occasionally, he pokes at one, but nothing happens.", actor_narrator}, [2] = {"So close, Koboltagonist. Progress bar half full. Or half empty?", actor_digmaster}, [3] = {"Bah, no matter. I sense third chamber is near. Look at what scouts bring to me.", actor_digmaster}, [4] = {"He holds up a massive tooth in his hand, its width double that of his palm.", actor_narrator}, [5] = {"Scouts dug deep into dry tunnels today. We thought nothing down there!", actor_digmaster}, [6] = {"Chamber door open already, by previous adventurer.", actor_digmaster}, [7] = {"Scouts were ambushed! HUGE boyo! Well, haven't seen with own eyes. But, scouts say it looked huge! Smelled huge!", actor_digmaster}, [8] = {"They say, too, that shiny object stuck in back. Part of hide. Shimmering, like them...", actor_digmaster}, [9] = {"He points to the glowing orange relic of the Slag King.", actor_narrator}, [10] = {"...you know what that means, Koboltagonist.", actor_digmaster}, [11] = {"Sadly, beast dragged scout back into chamber. Door shut once more. Not opened again.", actor_digmaster}, [12] = {"Vault so close! Progress bar close to full! No, partly empty!", actor_digmaster}, [13] = {"Go now. But, watch out big teeth.", actor_digmaster}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"You heave the heavy relic onto the pedastal, saving the Dig Master the trouble.", actor_narrator}, [2] = {"As it settles into the grip of its iron holster, a faint ringing can be heard, and each piece glows slightly brighter.", actor_narrator}, [3] = {"Ahhhh...", actor_digmaster}, [4] = {"The Dig Master rubs his hands together and grins.", actor_narrator}, [5] = {"Hopefully not too much trouble. How big beastie? Super big?", actor_digmaster}, [6] = {"He looks at you with curiosity. You're covered head to toe in a layer of thick dirt.", actor_narrator}, [7] = {"Ah, not so bad! Well, at least you okay!", actor_digmaster}, [8] = {"He slams you on the back, the dust flying everywhere.", actor_narrator}, [9] = {"Progress bar very close to done, Koboltagonist. Soon, we unlock greatest treasure in Kingdom history!", actor_digmaster}, [10] = {"Heard of ogres from cold tunnels. Made camp nearby. Rumor of last relic knowledge, but probably need favor.", actor_digmaster}, [11] = {"Try them. I get scouts and lead way to vault. We prepare. We plan for grand opening. Grand party!", actor_digmaster}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"No, it was a dragon!", actor_grog}, [2] = {"Lizard!", actor_slog}, [3] = {"Dragggoooonnnnn!", actor_grog}, [4] = {"The two ogres stare each other down with raised fists before noticing your tiny figure standing between them.", actor_narrator}, [5] = {"Baaah! What that!", actor_grog}, [6] = {"Just a kobold, Grog. He won't hurt ye', ya dolt.", actor_slog}, [7] = {"The blue ogre picks you up with a single hand and dangles you, his other hand pressed to his chin in contemplation.", actor_narrator}, [8] = {"Having almost been eaten by a giant, ancient dinosaur five times his size, you put on a display of absolutely no trepidation.", actor_narrator}, [9] = {"I like this one, Grog.", actor_slog}, [10] = {"He places you back down.", actor_narrator}, [11] = {"This be the Koboltagonist the Dig Masta been talkin' 'bout! Perfect for us'n, Grog.", actor_slog}, [12] = {"Dat pipsqueak ain't makin' me go back down 'der! Kobo'tagonist er' not.", actor_grog}, [13] = {"Whot?! You won't go down that wee lil' tunnel, but this lil' digging rat will?", actor_slog}, [14] = {"You nod once when the ogre looks to you.", actor_narrator}, [15] = {"Bah, fine, Grog, you overgrown baby. Why you even carry dat club around wichye? Should hand'it to this 'ere warrior rat instead!", actor_slog}, [16] = {"The tan ogre turns, waving a hand in disregard and looking the other way.", actor_narrator}, [16] = {"I ain't got it no more.", actor_grog}, [17] = {"Wha? You dropped it?! Can't even hold onto ye' club during a mild jog?", actor_slog}, [18] = {"Hmph!", actor_grog}, [19] = {"The blue ogre shakes his head in disappointment and turns to you.", actor_narrator}, [20] = {"Well, lil' rat, I'll have to stay here an' make sure Grog don't wander off down the wrong tunnel. He's bit scared of 'dat big lizard.", actor_slog}, [21] = {"Dig Master says ye' be looking for the last shiny rock. We knows where it is. We tells ye'.", actor_slog}, [22] = {"But first, needs something of ye'. I think Grog will get his grips back with his ol' club. Fetch it from the cold tunnels fors 'im, aye?", actor_slog}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"With a thud, you slam the hilt of the giant ogre club near the campfire.", actor_narrator}, [2] = {"The blue ogre looks at you and cracks a grin before looking to his companion, who takes the club effortlessly with one hand and wields it about.", actor_narrator}, [3] = {"Ahah! I tolds ye'! You lost, pay up!", actor_slog}, [4] = {"Bah, fine!", actor_grog}, [5] = {"Grog reaches into a nearby satchel and retrieves a sack of gold coins and places it in Slog's hand.", actor_narrator}, [6] = {"Hah! Oi, get your spirits up, mate. This lil' one just got your courage back. By 'imself, too!", actor_slog}, [7] = {"...", actor_grog}, [8] = {"You look on with notable indifference.", actor_narrator}, [9] = {"Ah, you ain't one for the silly bits, lil' rat. No problem 'ere.", actor_slog}, [10] = {"Looky 'ere, as promised. What yer lookin' for is down this abandon tunnel.", actor_slog}, [11] = {"He places a thin cloth on your hand featuring a rough map outlined with a shard of campfire coal.", actor_narrator}, [12] = {"Old magic used down there, long ago. Blue Dragonflight or a thing'a that nature. Some big creature, big lizard...", actor_slog}, [13] = {"...dragon...", actor_grog}, [14] = {"No matter, whatever 'tis! It's deadly. We ain't stayed to see what it was. You just be careful down there, y'hear?", actor_slog}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"Words spread like hot wax, Koboltagonist! We hear of good news.", actor_digmaster}, [2] = {"You hand the ogre's cloth map to the Dig Master.", actor_narrator}, [3] = {"Ah, deep within ice tunnels. Good! Faster we open last chamber, get last relic, faster we get treasure.", actor_digmaster}, [4] = {"Ogres good idea, glad I let them stay. How else we know of last piece?", actor_digmaster}, [5] = {"The Dig Master puts on a smug look and stands tall as he looks over his trophies. A little too smug.", actor_narrator}, [6] = {"He notices you watching him intently.", actor_narrator}, [7] = {"Aye, aye. All because of you, too. But I help too, this time. Ay?", actor_digmaster}, [8] = {"No time for idle-scrat, Koboltagonist. Go be Koboltagonist! You well trained for beasties now!", actor_digmaster}, [9] = {"Kobolds always send the best!", actor_digmaster}, [10] = {"Now ours, hehehehaha!", actor_digmaster}, [11] = {"*Cough*... Ahem...", actor_digmaster}, [12] = {"Off to the lizard-dragon, Koboltagonist!", actor_digmaster}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"The relic has returned! Oh, and Koboltagonist, too.", actor_digmaster}, [2] = {"The Dig Master rubs his hands together impatiently.", actor_narrator}, [3] = {"No time to wait. Place it! Place it! Place it!", actor_digmaster}, [4] = {"...", actor_digmaster}, [5] = {"...ahem. At your own pace, Koboltagonist. Right. We only have 'cause of you. Scrat! No manners.", actor_digmaster}, [6] = {"You approach the final pedastal with the glowing blue relic from the slain ice monster. The Dig Master inches forward as you do.", actor_narrator}, [7] = {"As you bend a knee to release it, a mysterious force rips it from your hands and slams it into place, knocking you back.", actor_narrator, nil, nil, nil, function() utils.looplocalp(function() StopSound(kui.sound.menumusic, false, true) end) end}, [8] = {"The four pieces link together in a series of elemental lights.", actor_narrator, nil, nil, nil, mergeancientrelics}, [9] = {"The artifacts' colors merge on the ground, forming a single slab of light.", actor_narrator}, [10] = {"In a flash, a beam projects upward to reveal a strange portal.", actor_narrator}, [11] = {"...", actor_narrator}, [12] = {"The light settles, and the room is quiet, save for the the monotonous hum of the portal.", actor_narrator}, [13] = {"You unshield your eyes, taking in the new scene.", actor_narrator}, [14] = {"You walk over to the slab of light. You feel the warmth as its energy, but nothing else occurs.", actor_narrator}, [15] = {"Bah, scrat!", actor_digmaster}, [16] = {"The Dig Master shuffles from underneath a table, returning to edge of the portal.", actor_narrator}, [17] = {"By all gold of Azeroth... well, what now?", actor_digmaster}, [18] = {"For the first time ever, the Dig Master remains still and quiet, contemplating the floor of light with one hand held to his chin.", actor_narrator}, [19] = {"He tries to move the relics, but they are firmly locked in place by a mysterious force.", actor_narrator}, [20] = {"After fidgeting with different objects and instruments, the Dig Master surrenders and throws up his arms.", actor_narrator}, [21] = {"Out of ideas, Koboltagonist.", actor_digmaster}, [22] = {"Scrat! Can't be end! Shouldn't be!", actor_digmaster}, [23] = {"So close!", actor_digmaster}, [24] = {"He rubs at his pockets several times.", actor_narrator}, [25] = {"Bah, no more cheese!", actor_digmaster}, [26] = {"You squint at him.", actor_narrator}, [27] = {"Wha'? Worth shot.", actor_digmaster}, [28] = {"The Dig Master sighs loudly and returns to his table to tinker.", actor_narrator}, [29] = {"A thought enters your mind of the old kobold and his scar. He must know more of what is required.", actor_narrator}, }) screenplay.chains.quest[idf()] = {} screenplay.chains.quest[id].start = speak.chain:build({ [1] = {"The Greywhisker sits on a petrified stone near his fire with both eyes shut.", actor_narrator}, [2] = {"He chants on occasion, to which the stones near the fire shift and its embers flare.", actor_narrator}, [3] = {"You take a seat on the opposite side of the pit and wait patiently.", actor_narrator}, [4] = {"He opens one eye for a moment, then shuts it again.", actor_narrator}, [5] = {"Such a sight, is it not? The relics of old, united once more. I have not seen it in many moons.", actor_greywhisker}, [6] = {"You stop prodding embers in the fire and look to the old mage.", actor_narrator}, [7] = {"Heh. It is not the first time that portal has graced this cavern.", actor_greywhisker}, [8] = {"Nearly three and ten winters ago, the old guard of 'mancers, and myself, set foot in that vault.", actor_greywhisker}, [9] = {"It was a different time. When us kobolds of the deep lacked proper earthly magic. We stood no chance.", actor_greywhisker}, [10] = {"And we were not the first. Many adventurers from the surface have attempted that place.", actor_greywhisker}, [11] = {"Evident by their bones that we scoured for loot.", actor_greywhisker}, [12] = {"We did not scavenge for long. The creaking and churning of gears caught our attention in the edge of the darkness.", actor_greywhisker}, [13] = {"That is when it struck. Not beast or of flesh, but of gold and jewels. Merged together over millennia, it would seem.", actor_greywhisker}, [14] = {"Contorted and twisted into a form that is only meant to punish those who seek it.", actor_greywhisker}, [15] = {"In the silence, embers pop and bursts of sparks float away. The echoes of picks on rock can be heard from deeper within the tunnel as kobolds work.", actor_narrator}, [16] = {"Do you think you will fare different, young one?", actor_greywhisker}, [17] = {"You frown and hold your pickaxe, rubbing at its silver edge.", actor_narrator}, [18] = {"I will not be the one to stand in your way. It was adventure and riches which I desired in my youth, and too many discouraged it.", actor_greywhisker}, [19] = {"I let their weakness stall my moment of glory.", actor_greywhisker}, [20] = {"The Greywhisker stands tall, cane in hand.", actor_narrator}, [21] = {"Is the vault what you desire?", actor_greywhisker}, [22] = {"You hesitate. A glimpse of gleaming gold fills your head.", actor_narrator}, [23] = {"You nod once.", actor_narrator}, [24] = {"So be it.", actor_greywhisker}, [25] = {"The Greywhisker pulls the prismatic gem from his staff and unties the leather of its hilt, the scabbard showing a luminous circle and strange letters.", actor_narrator}, [26] = {"This is the last of the old keys, and the human tongue that describes how to use it. However, it has long been drained of its power.", actor_greywhisker}, [27] = {"He hands you the cloth, which you place carefuly in your dig map.", actor_narrator}, [28] = {"This map will allow you to access |c0000f066The Vault|r through the portal, so long as you carry it, but not its core chamber.", actor_greywhisker}, [29] = {"You will need to gather enough |c00ff9c00Ancient Fragments|r so that I can imbue the prism with energy to reach the vault's depths.", actor_greywhisker}, [30] = {"Only when the vault's guardian is defeated can our kobolds secure its trove.", actor_greywhisker}, [31] = {"When you have acquired enough fragments, return to me, and we will see if you follow the path to glory, or the path to doom.", actor_greywhisker}, [32] = {"One of those roads has already been traveled between us. Let us hope it does not repeat itself...", actor_greywhisker}, }) screenplay.chains.quest[id].finish = speak.chain:build({ [1] = {"You step in front of the Dig Master, your clothing scorched by molten gold and your head burned clean of hair.", actor_narrator, nil, nil, nil, function() utils.stopsoundall(kui.sound.menumusic) end}, [2] = {"Bah!", actor_digmaster}, [3] = {"...", actor_digmaster}, [4] = {"Oh, Koboltagonist, didn't recognize. Thought you tunnel mole! Naked one, too!", actor_digmaster}, [5] = {"With a heavy grunt, you drop the solid gold head of the defeated amalgam on the table.", actor_narrator}, [6] = {"The Dig Master rushes to it, rubbing his hand over its raised brow and pointed teeth while staring into its two ruby sockets.", actor_narrator}, [7] = {"By skirt—I mean drat—I mean scrat, by dirt!", actor_digmaster}, [8] = {"He pauses and looks to you from the corner of his eye, per usual.", actor_narrator}, [9] = {"More?", actor_digmaster}, [10] = {"You nod, then point to your map with the runic scabbard, then to the portal. You hand the cloth to the Dig Master.", actor_narrator}, [11] = {"Yes, yes! I get Shinykeeper and diggers, we leave first thing!", actor_digmaster}, [12] = {"You done good Koboltagonist.", actor_digmaster}, [13] = {"The Dig Master nearly knocks over his table as he rummages for bags and buckets, stacking and tying them them atop his giant rat steed.", actor_narrator}, [14] = {"As he comes to a halt—his head now also hosting a silver bucket—he glances to you with eager eyes.", actor_narrator}, [15] = {"...", actor_digmaster}, [16] = {"Koboltagonist? You come? Need more buckets!", actor_digmaster}, [17] = {"You nod.", actor_narrator, nil, nil, nil, function() utils.fadeblack(true, 2.0) end}, [18] = {"Before long, the Dig Master is gone, making a head start for the great vault through the portal with the Shinykeeper, Elementalist, and diggers in tow.", actor_narrator}, [19] = {"You look around, frst to the Shinykeeper's forge, then to the infusion crystals lining the back wall.", actor_narrator}, [20] = {"No other kobolds are in sight. The main tunnel looks to have been left temporarily unattended in the mad dash to the treasure room.", actor_narrator}, [21] = {"You go to see the Greywhisker, but he is not near his camp. His tent is packed and gone, and the fire pit doused.", actor_narrator}, [22] = {"You ponder his intentions, but are distracted by the thought of the conquests achieved this day.", actor_narrator}, [23] = {"Something inside you yearns for it again.", actor_narrator}, [24] = {"But, later. Rest is well-earned. You did a lot today, for a tiny rat with a candle and pickaxe.", actor_narrator}, [25] = {"With an unabashed grin, you grab your rucksack, shoulder your trusty tool, and make for the vault portal at a slow and steady pace.", actor_narrator}, [26] = {"You near the Dig Master's table, where the ogre's club has been placed for whatever reason. They appear to have joined in on the treasure hunt.", actor_narrator}, [27] = {"As you pass by, the chisel of your pickaxe swings outward from your stride and knocks over the brutish ogre's club.", actor_narrator}, [28] = {"Its stone head cracks open from the impact. You look around, but there's still no one.", actor_narrator}, [29] = {"As you shrug and take a step to leave, you catch a reflection from the wreckage.", actor_narrator}, [30] = {"You reach down to the cracked mallet, tossing it with one hand. It crumbles into dust, leaving only a strange, purple orb.", actor_narrator}, [31] = {"It pulsates with dark swirls of black and magenta.", actor_narrator}, [32] = {"You bend down and rub its surface with loose fingers. Something inside it calls to you.", actor_narrator}, [33] = {"You hesitate. After a short delay, you pick it up and place it in your pack.", actor_narrator}, [34] = {"But, that's for another day.", actor_narrator}, [35] = {"", actor_narrator, nil, nil, nil, function() speak:show(false, true) speak.showskip = true utils.playsoundall(kui.sound.completebig) alert:new(color:wrap(color.tooltip.alert, "The End|n")..color:wrap(color.tooltip.good, " Thanks for playing!"), 7.5) utils.timed(9.0, function() utils.fadeblack(false, 2.0) speak:endscene() end) utils.timed(11.0, function() utils.playsoundall(kui.sound.menumusic) end) end}, }) end
package com.generation.lojadegames.controller; import java.util.List; import java.util.Optional; import javax.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.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import com.generation.lojadegames.model.Usuario; import com.generation.lojadegames.model.UsuarioLogin; import com.generation.lojadegames.repository.UsuarioRepository; import com.generation.lojadegames.service.UsuarioService; @RestController @RequestMapping("/usuarios") @CrossOrigin(origins = "*", allowedHeaders = "*") public class UsuarioController { @Autowired private UsuarioService usuarioService; @Autowired private UsuarioRepository usuarioRepository; @PostMapping("/logar") public ResponseEntity<UsuarioLogin> Autentication(@RequestBody Optional<UsuarioLogin> user){ return usuarioService.autenticarUsuario(user) .map(resposta -> ResponseEntity.ok(resposta)) .orElse(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } @PostMapping("/cadastrar") public ResponseEntity<Usuario> Post(@RequestBody Usuario usuario) { return usuarioService.cadastrarusuario(usuario) .map(respostacadas -> ResponseEntity.status(HttpStatus.CREATED).body(respostacadas)) .orElse(ResponseEntity.status(HttpStatus.BAD_REQUEST).build()); } @GetMapping public ResponseEntity<List<Usuario>> getAll(){ return ResponseEntity.ok(usuarioRepository.findAll()); } @GetMapping("/{id}") public ResponseEntity<Usuario> getById(@PathVariable Long id){ return usuarioRepository.findById(id) .map(resposta -> ResponseEntity.ok(resposta)) .orElse(ResponseEntity.notFound().build()); } @GetMapping("/nome/{nome}") public ResponseEntity<List<Usuario>> getByNome(@PathVariable String nome){ return ResponseEntity.ok(usuarioRepository.findAllByNomeContainingIgnoreCase(nome)); } @PostMapping public ResponseEntity<Usuario> postUsuario(@Valid @RequestBody Usuario usuario){ return ResponseEntity.status(HttpStatus.CREATED).body(usuarioRepository.save(usuario)); } @PutMapping public ResponseEntity<Usuario> putUsuario(@Valid @RequestBody Usuario usuario){ return usuarioRepository.findById(usuario.getId()) .map(resposta -> ResponseEntity.ok(usuarioRepository.save(usuario))) .orElse(ResponseEntity.notFound().build()); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping("/{id}") public void deleteUsuario(@PathVariable Long id) { Optional<Usuario> post = usuarioRepository.findById(id); if(post.isEmpty()) throw new ResponseStatusException(HttpStatus.BAD_REQUEST); usuarioRepository.deleteById(id); } }
package hr.fer.zemris.java.hw06.shell.commands; import java.util.Collections; import java.util.LinkedList; import java.util.List; import hr.fer.zemris.java.hw06.shell.Environment; import hr.fer.zemris.java.hw06.shell.ShellCommand; import hr.fer.zemris.java.hw06.shell.ShellStatus; /** * Used to terminate MyShell. * * @author Florijan Rusac * @version 1.0 */ public class ExitShellCommand implements ShellCommand { @Override public ShellStatus executeCommand(Environment env, String arguments) { String[] args = Util.splitArguments(arguments); if (args.length != 0) { env.writeln("Invalid command argument."); return ShellStatus.CONTINUE; } return ShellStatus.TERMINATE; } @Override public String getCommandName() { return "exit"; } @Override public List<String> getCommandDescription() { List<String> list = new LinkedList<>(); list.add("Used to terminate MyShell."); return Collections.unmodifiableList(list); } }
import { useEffect, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { useNavigate } from 'react-router-dom' // FPCC import { useSiteStore } from 'context/SiteContext' import api from 'services/api' import immersionDataAdaptor from 'components/Immersion/immersionDataAdaptor' function DashboardImmersionData() { const { site } = useSiteStore() const { sitename, children, id } = site const navigate = useNavigate() const [labelDictionaryId, setLabelDictionaryId] = useState(null) useEffect(() => { if (children?.['Label Dictionary']) setLabelDictionaryId(children['Label Dictionary']) }, [children]) const { isInitialLoading, error, isError, data } = useQuery( ['immersion', id], () => api.immersion.get(labelDictionaryId), { // The query will not execute until the labelDictionaryId exists enabled: !!labelDictionaryId, }, ) useEffect(() => { if (isError) { navigate( `/${sitename}/error?status=${error?.response?.status}&statusText=${error?.response?.statusText}&url=${error?.response?.url}`, { replace: true }, ) } }, [isError]) const tileContent = [] const headerContent = { title: 'Immersion', subtitle: 'Update the labels used in immersion mode on your site.', icon: 'Translate', iconColor: 'tertiaryA', } return { headerContent, isLoading: isInitialLoading || isError, site, tileContent, labels: immersionDataAdaptor(data) || [], } } export default DashboardImmersionData
pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; contract Stems is ERC721, Ownable, ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _tokenNums; event ForagedStem( address indexed _forager, uint256 indexed _tokenId ); uint256 public nextTokenId; uint256 public lastTokenId; uint256 public stemPriceInWei; uint256 public maxStems; string public baseURI; string public baseIpfs; string public scriptJson; string public script; uint256 private nonce; mapping (bytes32 => uint256) public hashToId; mapping (uint256 => bytes32) internal idToHash; mapping (uint256 => string) public _tokenURIs; bool private is_dis_on; constructor(uint256 _stemPriceInWei, uint256 _maxStems) ERC721('andStems','STEMS') { maxStems = _maxStems; stemPriceInWei = _stemPriceInWei; } modifier started() { require(is_dis_on, "Contract must be started in order to ape."); _; } modifier stopped() { require(!is_dis_on, "Contract needs to be stopped fren."); _; } modifier apeable() { require(_tokenNums.current() + 1 <= maxStems, "Value error."); require(msg.value == stemPriceInWei, "Value error. Please try to ape again after thinking on it."); _; } function on_off_button() public onlyOwner returns (bool) { is_dis_on = !is_dis_on; return true; } function updatePrice(uint256 _stemPriceInWei) public onlyOwner stopped returns (bool) { stemPriceInWei = _stemPriceInWei; return true; } function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { return ERC721URIStorage._burn(tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return ERC721URIStorage.tokenURI(tokenId); } function mintStem() external payable started apeable returns (uint256 _tokenId) { address _forager = msg.sender; uint256 tokenId = _mintStem(_forager); return tokenId; } function _mintStem(address _forager) internal returns (uint256) { _tokenNums.increment(); uint256 _tokenId = _tokenNums.current(); bytes32 hash = keccak256(abi.encodePacked(_tokenId, block.number, blockhash(block.number - 1), msg.sender)); idToHash[_tokenId] = hash; hashToId[hash] = _tokenId; _safeMint(_forager, _tokenId); _setTokenURI(_tokenId, _baseURI()); emit ForagedStem(_forager, _tokenId); return _tokenId; } function _baseURI() internal view override returns (string memory) { return 'https://frozen-crag-92247.herokuapp.com/'; } }
import { useState } from "react" import toast from "react-hot-toast" import { useNavigate } from "react-router-dom" import useAppContext from "../../hooks/useAppContext" function CreateProfile() { const navigate = useNavigate() const [states] = useState([ { name: "Andhra Pradesh", cities: ["Visakhapatnam", "Vijayawada", "Hyderabad"], }, { name: "Assam", cities: ["Guwahati", "Dibrugarh", "Silchar"] }, { name: "Bihar", cities: ["Patna", "Gaya", "Muzaffarpur"] }, // Add more states and cities as needed ]) const [rememberMe, setRememberMe] = useState(false) const [formData, setFormData] = useState({ fullName: "", emailAddress: "", companyName: "", selectedState: "", selectedCity: "", sponsorCode: "ABC123", }) const { setUserData } = useAppContext() const handleOnChange = (e) => { const { name, value } = e.target setFormData({ ...formData, [name]: value }) } const handleGoBack = () => { navigate("/") } const validateForm = () => { const { fullName, emailAddress, companyName, selectedState, selectedCity, sponsorCode, } = formData if (!fullName) { toast.error("Please enter your full name") return false } else if (!emailAddress) { toast.error("Please enter your email address") return false } else if (!companyName) { toast.error("Please enter your company name") return false } else if (!selectedState) { toast.error("Please select your state") return false } else if (!selectedCity) { toast.error("Please select your city") return false } else if (!sponsorCode) { toast.error("Please enter your sponsor code") return false } return true } const handleProfileUpdate = async () => { if (!validateForm()) return const token = localStorage.getItem("token") if (token) { try { // API does not exist confirm with backend team // const API = import.meta.env.VITE_BE_API // const response = await axios.post( // `${API}/api/profile/store`, // formData, // { // headers: { Authorization: `Bearer ${token}` }, // } // ) // toast.success(response.data.message) // directly store in frontend if (rememberMe) { localStorage.setItem("userData", JSON.stringify(formData)) } setUserData(formData) sessionStorage.removeItem("newUser") navigate("/profile/created") } catch (error) { toast.error("Email already exists") console.error("Profile update failed:", error) } } } return ( <div className="w-full bg-green-100 flex justify-center items-center px-4 py-8"> <div className="w-full sm:w-[500px] bg-white flex flex-col gap-3 rounded-2xl shadow-2xl"> <div className="text-darkGreen text-xl flex items-center justify-between rounded-2xl py-4 px-5"> <i onClick={handleGoBack} className="cursor-pointer text-darkGreen fa-solid fa-chevron-left fa-xl" ></i> <h1 className="font-bold text-2xl pt-4 text-center w-full"> Create Profile </h1> </div> {/* input fields */} <div className="px-8 pb-4 w-full flex flex-col justify-center gap-2"> <div className="input-group"> <label htmlFor="" className="text-slate-800 font-semibold" > Full name </label> <input className="input-field" type="text" placeholder="Enter full name" value={formData.fullName} name="fullName" onChange={handleOnChange} /> </div> <div className="input-group"> <label htmlFor="" className="text-slate-800 font-semibold" > Email address </label> <input className="input-field" type="email" placeholder="Enter email address" value={formData.emailAddress} name="emailAddress" onChange={handleOnChange} /> </div> <div className="input-group"> <label htmlFor="" className="text-slate-800 font-semibold" > Company Name </label> <input className="input-field" type="text" placeholder="Company Name" value={formData.companyName} name="companyName" onChange={handleOnChange} /> </div> <div className="flex gap-2 w-full"> <div className="input-group w-full"> <label htmlFor="" className="text-slate-800 font-semibold" > State </label> <select className="input-field" value={formData.selectedState} name="selectedState" onChange={handleOnChange} > <option value="">Select State</option> {states.map((state, index) => ( <option key={index} value={state.name}> {state.name} </option> ))} </select> </div> <div className="input-group w-full"> <label htmlFor="" className="text-slate-800 font-semibold" > City </label> <select className="input-field" value={formData.selectedCity} name="selectedCity" onChange={handleOnChange} > <option value="">Select City</option> {states .find( (state) => state.name === formData.selectedState ) ?.cities.map((city, index) => ( <option key={index} value={city}> {city} </option> ))} </select> </div> </div> <div className="input-group"> <label htmlFor="" className="text-slate-800 font-semibold" > Sponsor code </label> <input className="input-field" type="text" placeholder="Sponsor Code" value={formData.sponsorCode} name="sponsorCode" onChange={handleOnChange} /> </div> <label className="flex gap-3 text-start pt-4"> <input type="checkbox" checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} /> Remember Me </label> <button className="my-3 w-[170px] bg-darkGreen hover:bg-green-600 duration-200 shadow-xl rounded-md py-2 px-4 text-white font-semibold self-center" onClick={handleProfileUpdate} > Create Profile </button> </div> </div> </div> ) } export default CreateProfile
import { LAYOUT_CONFIG } from "@angular/flex-layout"; import Pokemon from "../Interfaces/Pokemon"; import Carapuce from "./Carapuce"; import Pokeball from "./Pokeball"; export default class Dresseur { private nom: string; pokeballs: Pokeball[] = []; /** * Ajoute des pokeballs si la limite n'est pas atteinte (6) * @param newPokeball */ public ajouterPokeballs(newPokeball: number): void { if (this.pokeballs.length >= 5) { console.log("Plus de place pour des pokeballs"); } else { for (let i = 0; i < newPokeball; i++) { if (this.pokeballs.length <= 5) { this.pokeballs.push(new Pokeball()) } else{ console.log("Vous ne pouvez pas avoir plus de 6 pokeballs"); } } } } /** * Retourne le nb de pokeball * @returns */ public havePokeball() { return this.pokeballs.length } /** * Permet de capturer un pokemon * @param pokenom */ public capturer(pokenom: Pokemon) { if(pokenom.captif == false){ console.log(`${this.nom} tente de capturer ${pokenom.nom}`); if (this.getPokeballs()) { this.fillEmptyPokeball(pokenom, this) }else{ console.log("Plus assez de pokeball, veuillez en rajouter"); } } else{ console.log(`${pokenom.nom} est déjà capturé et ne peut pas l'être de nouveau`); } } /** * Remplie une pokeball vide en lui attribuant un pokemon et une pokeball * @param cible * @param dresseur */ private fillEmptyPokeball(cible: Pokemon, dresseur: Dresseur) { let i: number = 0; for (i; i < this.pokeballs.length; i++) { if (this.pokeballs[i].isEmpty()) { this.pokeballs[i].contient = cible; this.pokeballs[i].propretaire = dresseur; cible.captif = true; console.log(`${cible.nom} a bien été capturé`); break; } } } /** * Affiche le contenu des pokeballs ayant un pokemon dedans */ public getPokemons(): void { let i: number = 0; for (i; i < this.pokeballs.length; i++) { if(!this.pokeballs[i].isEmpty()){ console.log(`Le contenu de la pokeball ${i} est ` + this.pokeballs[i].contient.nom); } } } /** * Permet de savoir s'il reste des pokeballs * @returns */ public getPokeballs(): boolean { let i: number = 0; if (this.havePokeball() < 5) { for (i; i < this.pokeballs.length; i++) { if (this.pokeballs[i].isEmpty()) { return true; } } } return false; } constructor(nom: string) { this.nom = nom; } get getNom() { return this.nom; } }
<apex:page > Fields : 1.Fields are nothing but the columns in the regular database. 2.There are two types of fields. a. Standard Fields b. Custom Fields 3.Standard Fields : a. These are the fields created by salesforce. b. Values can be entered by the users or system. c. If the System auto generates the value ,Then those fields are called system fields. 4.System Fields : a.There are the standard fields which are created by salesforce b. Data is also created and updated by the System c. There are 7 System Fields 1. ID : a.Salesforce by default creates 15 Character unique Id for every record. b.This Id is case-sensitive. c.Three more charcters are added to make it case-in-sensitive Id . d.This id is also called as primary key e.First three characters represent object. f.Last four characters represent record. 2. isDeleted : a. This is boolean field. b. Value of this field is set as true,when the record was deleted. c. When a record is deleted,Record will be in the object for 15 days. d. After 15days record will be deleted permanently. 3. CreatedById a. This filed will store the 18 character Id of the user who created this record . 4. LastModifiedById a. This field will store the 18 character Id of the user who lastly modified this record 5. CreatedDate : a. This field will store date and time when the record was created . 6. LastModifiedDate : a. This field will store date and time when the record was lastly modified manualy. 7. SystemModStamp a. This field will store date and time when the record was lastly modified manualy or programatically 5. Which fields we call as System Audit Fields ? a.CreatedById b.LastModifiedById c.CreatedDate d.LastModifiedDate e.SystemModStamp 6: Custom Fields : a.These are the fields which are created by the user to meet his organizational business requirement. b. Salesforce has defined predefined datatypes to create the custom fields 1. Text : Format : Alphanumeric MaxLength : 255 Characters Single|Multiple : Single Line 2. TextArea: Format : AlphaNumeric MaxLength : 255 Characters Single|Multiple : Multiple Line 3. TextArea(Long) : Format : AlphaNumeric MaxLength : 1,31,072 Characters Defualt : 32,768 characters Minimum Length : 256 Characters Single|Multiple : Multiple 4. TextArea(Rich) : Format : Formated Data Max Length : 1,31,072 characters Default Length : 32,768 Characters Minimum Lines : 10 Lines 5. Phone : This data type is used to store the phone numbers 6. CheckBox : This data types will store the value of true or false 7. Currency : Currency values are stored in this fields . Max Length : (Length of Integer +Length of Decimal ) should be at max 18 characters Ex : 32000.20 ( 5+2= 7) 8. Date : This field will store a particular in the calender . 9. DateTime : This field will store the particular day and time from the calender . 10.Number : These fields are used to store numerical values Max Length : 18 characters( Length of Integer+length of Decimal) 11.Percent : These fields are used to store the percentage value ,by defualt '%' symbol is appended to the data . Max Length : 18 characters( Length of Integer+length of Decimal) 12.Email : These field will store the email id's , Note : Salesforce has defined validation rules to check the format of the email address. 13. PickList : a. It is a dropdown list from which we can select one option at a time . b. Maximum we can provide 1000 options . c. Length of each option can be 255 characters d. All the options together can be 15000 characters. e. We can sort options in the accending order. f. We can make the first option as defualt option by enabling the field. g. We can add /remove/edit /reorder the options based on business requirement. 14. PickList( Multi-Select) : a. It is also a picklist field but we can select more than one option at a time . b. We can at max provide 150 options . c .Maximum we select 100 options . d. Length of each option can be at max 40 characters e. All the options together can be 1500 characters. 15 .Text Encrypted : a. When we want to save the data in the encrypted format ,we use data Type TextEncrypted b. Maximum length of the field is 175 characters . c. By default no one can access the data in the orginal format , d. If you want to see the data in the orginal format ,users profile should have view encrypted data permission enabled e. Text encrypted fields can not be used in formulas f. Encrypted fields can not be used in search Criteria or filterConditon g. Encrypted fields can be used in validations ,search results, report results. Q:: In How many ways we can create Custom Fields Ans : Three ways a. Standard Navigation : Classic : Setup |--->Build |--->Create |--->Object |--->Object Name |--->Custom Fields and Relations |---->New Lightning : Setup |---> Platform Tools |---> Object Manager |---> Choose the object |--->Fields and Relations |---> New Step 1: Choose the dataType Step 2: Enter field Details Like (Label,Name,Required, Unique) Step 3: Choose the Field Level security Step 4: Add the field to the default Layout . b. Schema Builder Classic : Setup |---> Build |---> Lightning Bolt |---> Schema Builder Lightning : Setup |---> Platform Tools |---> Object and Relations |---> Schema Builder Step 1: Choose the Object. Step 2: Choose the datatype Step 3: Enter the field Details Step 4: Save c. Force.com ShortCut Menu in classic. Step 1: Click on the Tab Step 2: Select Force.com Menu Step 3: Choose view fields Step 4: Select Custom Fields and Relations Step 5: Select new and create the fields. Note : We can also create fields using Metadata Soap api webservice 17. Field Dependency : 1.If you want to controll the values of one field by using another field then we use field dependency. 2.Controlling Field : a.we can choose the any of PickList Field and Checkbox field as controlling field. b. If we choose any picklist field as controlling field ,then picklist field can have only 300 options in it . 3.Dependent Field :We can choose PicklIst /MultiSelect PicKList field as Dependent field. 4. We can create multilevel dependency. 5.Steps to create fiel dependency Classic : Setup |--->Build |--->Create |--->Objects |---> Fields and Relations |---> Field Dependencies Lightning : Setup |--->Platform tools |--->Objects and Relations |---> Object Manager |--->Choose Object |---> Fields and Relations |---> Field Dependencies Step 1: Select the Controlling Field Step 2: Choose the Dependent field Step 3: Include and Execlude the dependent options for the Controlling Field. Step 4: Save . UseCase : Create a Custom Object Customer : Create Two Custom Fields Field Name DataType Options City PickList Hyd,Ban,Che Places PickList SRNagar,LBNagar Chromepet,Thambaram ECity,Marthali Create a field dependency. 18. PickList set : if you want to add same set of options to multiple picklist fields then we use Picklist set . Classic : Setup |--->Build |---> Create |---> PickList value set Lightning : Setup |---> Platform Tools |---> Objects and Relations |---> Picklist value set Step 1: Enter the set name Step 2: Enter the options Step 3: save Note : If we create the fields using schema builder fields will not be diplayed on the ui we need to add the fields to the pagelayout . </apex:page>
<template> <CRow> <CCol sm="12" md="12"> <CCard accent-color="primary"> <b-row class="mt-3 mx-1"> <b-col> <h4 class="text-center">{{$t('ReportColorRatingOfSchools')}}</h4> </b-col> </b-row> <CCardHeader> <b-row> <b-col> <div> <label> {{ $t('SchoolYear') }} </label> <v-select :options="schoolyearlist" v-model="filter.schoolyearid" :reduce="item => item.id" :placeholder="$t('SchoolYear')" label="name" > </v-select> </div> </b-col> <b-col> <div> <label> {{ $t('oblast') }} </label> <v-select :options="OblastList" v-model="filter.oblastid" :disabled="!$can('AdminView', 'permissions') && !$can('MinSportView', 'permissions') && $can('OblastSport', 'permissions') || $can('RegionXTB', 'permissions')" :reduce="item => item.id" :placeholder="$t('oblast')" label="name" class="mr-2" style="width:100%" @input="changeOblast()" ></v-select> </div> </b-col> <b-col> <div> <label> {{ $t('region') }} </label> <v-select :options="RegionList" v-model="filter.regionid" :disabled="!$can('AdminView', 'permissions') && !$can('MinSportView', 'permissions') && !$can('OblastSport', 'permissions') && $can('RegionXTB', 'permissions')" :reduce="item => item.id" :placeholder="$t('region')" label="name" class="mr-2" style="width:100%" @input="changeRegion()" ></v-select> </div> </b-col> <b-col> <div class="d-flex"> <CButton @click="Refresh" size="sm" color="primary" class="mr-2" style="margin-top:27px" > <b-icon icon="arrow-repeat"> </b-icon> {{ $t('Refresh') }} </CButton> <CButton @click="Print" color="primary" size="sm" class="mr-2" style="margin-top:27px" > <b-icon icon="printer"></b-icon> &nbsp; {{ $t("Export") }} </CButton> <CButton color="danger" @click="backbyregion" size="sm" class="mr-2" style="margin-top:27px" > <b-icon icon="arrow-left-short" ></b-icon> {{$t('back')}} </CButton> </div> </b-col> </b-row> <CRow class="form-group"> <CCol lg="4" md="6" sm="6" class="text-left mt-2 pl-0"> </CCol> </CRow> <CRow class="form-group"> <CCol > <h4 class="region-text"> <a href="javascript:void(0)" @click="topcountrychange">{{$t('O`zbekiston')}}</a> <a href="javascript:void(0)" @click="topoblastchange" >{{filter.OblastName}}</a> <a href="javascript:void(0)" >{{filter.RegionName}}</a> </h4> </CCol> </CRow> </CCardHeader> <div class="table-container" style="padding:5px"> <table class="table table-bordered "> <thead> <tr> <th rowspan="2" v-if="filter.oblastid===0 || filter.oblastid===null" style="text-align: center;vertical-align: middle">{{$t('oblastname')}}</th> <th rowspan="2" v-if="filter.oblastid>0 && (filter.regionid === 0 || filter.regionid === null) && !filter.byschool" style="text-align: center;vertical-align: middle">{{$t('regionname')}}</th> <th rowspan="2" v-if="filter.oblastid>0 && (filter.regionid === 0 || filter.regionid === null) && filter.byschool" style="text-align: center;vertical-align: middle">{{$t('organizationname')}}</th> <th rowspan="2" v-if="filter.oblastid>0 && filter.regionid>0" style="text-align: center;vertical-align: middle">{{$t('organizationname')}}</th> <th colspan="3" style="text-align: center;vertical-align: middle">{{$t('Students')}}</th> <th colspan="3" style="text-align: center" >{{$t('Schools')}}</th> </tr> <tr> <th style="text-align: center;vertical-align: middle">{{$t('totalcount')}}</th> <th style="text-align: center" >{{$t('enrolledcount')}}</th> <th style="text-align: center;vertical-align: middle">{{$t('enrolledpercent')}}</th> <th style="text-align: center;vertical-align: middle">{{$t('redschool')}}</th> <th style="text-align: center" >{{$t('yellowschool')}}</th> <th style="text-align: center;vertical-align: middle">{{$t('greenschool')}}</th> </tr> </thead> <tbody v-if="!Loading"> <tr v-for="(item,i) in items" style="text-align: center;vertical-align: middle" :key="i" :class=" item.enrolledpercent < 10 ? 'isreconstructed-danger' : item.enrolledpercent >= 10 && item.enrolledpercent < 30 ? 'isreconstructed-warning' : item.fillcoef >= 30 ? 'isreconstructed-success' : 'isreconstructed-success'" > <td v-if="filter.oblastid===0 || filter.oblastid===null" style="text-align: left;vertical-align: middle" > <a href="javascript:void(0)" @click="oblastchange(item)">{{item.oblastname}}</a> </td> <td v-if="filter.oblastid>0 && (filter.regionid === 0 || filter.regionid === null) && !filter.byschool" style="text-align: left;vertical-align: middle"> <a href="javascript:void(0)" @click="regionchange(item)">{{item.regionname}}</a> </td> <td v-if="filter.oblastid>0 && (filter.regionid === 0 || filter.regionid === null) && filter.byschool" style="text-align: left;vertical-align: middle" > <a href="javascript:void(0)">{{item.organizationname}}</a> </td> <td v-if="filter.oblastid>0 && filter.regionid > 0" style="text-align: left;vertical-align: middle" > <a href="javascript:void(0)">{{item.organizationname}}</a> </td> <td >{{item.totalcount}}</td> <td >{{item.enrolledcount}}</td> <td >{{item.enrolledpercent}}</td> <td >{{item.redschool}}</td> <td >{{item.yellowschool}}</td> <td >{{item.greenschool}}</td> </tr> <tr style="text-align: center;vertical-align: middle;font-weight: bold"> <td >{{$t('Total')}}</td> <td>{{bottomrow.totalcount== 0?'-': $options.filters.currency(bottomrow.totalcount, {symbol: '', fractionCount: 0})}}</td> <td>{{bottomrow.enrolledcount== 0?'-': $options.filters.currency(bottomrow.enrolledcount, {symbol: '', fractionCount: 2})}}</td> <td>{{bottomrow.enrolledpercent== 0?'-': $options.filters.currency(bottomrow.enrolledpercent, {symbol: '', fractionCount: 2})}}</td> <td>{{bottomrow.redschool== 0?'-': $options.filters.currency(bottomrow.redschool, {symbol: '', fractionCount: 0})}}</td> <td>{{bottomrow.yellowschool== 0?'-': $options.filters.currency(bottomrow.yellowschool, {symbol: '', fractionCount: 2})}}</td> <td>{{bottomrow.greenschool== 0?'-': $options.filters.currency(bottomrow.greenschool, {symbol: '', fractionCount: 2})}}</td> </tr> </tbody> <tbody v-if="Loading"> <tr> <td class="text-center" colspan="19"> <b-spinner></b-spinner> </td> </tr> </tbody> </table> <br> </div> </CCard> </CCol> </CRow> </template> <script> import SchoolYearService from "@/services/SchoolYear.service"; import OblastService from "@/services/Oblast.service"; import RegionService from "@/services/Region.service"; import ReportColorRatingOfSchoolsService from "@/services/ReportColorRatingOfSchools.service"; export default { data() { return { schoolyearlist: [], OblastList: [], RegionList: [], items: [], Loading : false, totalRows: "", isBusy: true, bottomrow: { totalcount: 0, enrolledcount: 0, enrolledpercent: 0 , redschool: 0, yellowschool: 0, greenschool: 0 }, filter: { schoolyearid: 3, oblastid: 0, regionid: 0, OblastName:'', RegionName:'', }, lang : localStorage.getItem('locale') || 'ru' }; }, created() { SchoolYearService.GetAll().then(res => { this.schoolyearlist = res.data; }); OblastService.GetAll().then((res) => { this.OblastList = res.data; }); this.createDate(); this.Refresh(); }, methods: { backbyregion(){ if(!!this.filter.oblastid && !this.filter.regionid){ this.filter.oblastid = 0 this.filter.OblastName = "" } if(!!this.filter.oblastid && !!this.filter.regionid){ this.filter.regionid = 0 this.filter.RegionName = "" } }, getregionlist(oblastid, setregionlist) { RegionService.GetAll(this.lang,this.filter.oblastid).then(res => { setregionlist(res.data); }); }, createDate() { var todaydate = new Date(); var dd = String(todaydate.getDate()).padStart(2, "0"); var mm = String(todaydate.getMonth() + 1).padStart(2, "0"); var yyyy = todaydate.getFullYear(); this.filter.ondate = dd + "." + mm + "." + yyyy; }, topcountrychange() { this.filter.oblastid = 0; this.filter.OblastName = ""; this.filter.RegionName = ""; }, topoblastchange() { this.filter.regionid = 0; this.filter.RegionName = ""; }, oblastchange(item) { this.filter.oblastid = item.oblastid; this.filter.OblastName = ' / '+ item.oblastname; }, regionchange(item) { this.filter.regionid = item.regionid; this.filter.RegionName = ' / '+item.regionname; }, Print() { ReportColorRatingOfSchoolsService.Print( this.filter.schoolyearid, this.filter.oblastid, this.filter.regionid) .then((response) => { var fileURL = window.URL.createObjectURL( new Blob([response.data], response.headers) ); var fileLink = document.createElement("a"); fileLink.href = fileURL; fileLink.setAttribute("download", "ReportTarifficationData.xlsx"); fileLink.click(); }) .catch((e) => { let response = JSON.parse(e.request.response); self.makeToast(response.error, self.$t("actions.error"), "danger"); }); }, Refresh() { this.Loading = true ReportColorRatingOfSchoolsService.GetColorRatingOfSchoolsByOblast( this.filter.schoolyearid, this.filter.oblastid, this.filter.regionid, ).then(res => { this.Loading = false this.items = res.data.data; if (res.data.oblastid > 0){ this.filter.OblastName = " / " + res.data.oblastname; this.filter.oblastid = res.data.oblastid; RegionService.GetAll(this.lang, this.filter.oblastid).then( (res) => { this.RegionList = res.data; } );} if (res.data.regionid > 0){ this.filter.oblastid = res.data.oblastid; this.filter.regionid = res.data.regionid; this.filter.RegionName = " / " + res.data.regionname; RegionService.GetAll(this.lang, this.filter.oblastid).then( (res) => { this.RegionList = res.data; } ); } this.bottomrow= { doctabcount: 0, doctabsum: 0 } this.calculateTotal(this.items) }); }, calculateTotal(item){ var totalcount= 0; var enrolledcount= 0; var greenschool= 0; var redschool= 0; var yellowschool= 0; var greenschool= 0; item.forEach(function (item) { totalcount = totalcount + item.totalcount; enrolledcount = enrolledcount + item.enrolledcount; redschool = redschool + item.redschool; yellowschool = yellowschool+ item.yellowschool; greenschool = greenschool+ item.greenschool; }); this.bottomrow= { totalcount : totalcount, enrolledcount: enrolledcount, enrolledpercent: this.roundToTwo(enrolledcount*100/totalcount, 0), redschool : redschool, yellowschool: yellowschool, greenschool: greenschool, } }, ChangeOblast() { if (!!this.filter.oblastid) { RegionService.GetAll(this.lang, this.filter.oblastid).then((res) => { this.RegionList = res.data; }); } }, makeToast(message, title, type) { this.toastCount++; this.$bvToast.toast(message, { title: title, autoHideDelay: 2000, variant: type, solid: true }); }, roundToTwo(value, decimals) { value; decimals; return Number(Math.round(value + "e" + decimals) + "e-" + decimals); }, }, watch: { "filter.oblastid": { handler(newValue, oldValue) { if (newValue) { this.items = []; this.bottomrow= { doctabcount: 0, doctabsum: 0 } this.filter.regionid = 0; } this.Refresh(); }, }, "filter.regionid": { handler(newValue, oldValue) { if (newValue) { this.items = []; this.bottomrow= { doctabcount: 0, doctabsum: 0 } } this.Refresh(); } }, } }; </script>
# Import Splinter, BeautifulSoup, and Pandas from splinter import Browser from bs4 import BeautifulSoup as soup import pandas as pd import time import datetime as dt from webdriver_manager.chrome import ChromeDriverManager def scrape_all(): # Initiate headless driver for deployment executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser('chrome', **executable_path, headless=True) news_title, news_paragraph = mars_news(browser) # Run all scraping functions and store results in a dictionary data = { "news_title": news_title, "news_paragraph": news_paragraph, "featured_image": featured_image(browser), "facts": mars_facts(), "hemisphere" : mars_hemispheres(browser), "last_modified": dt.datetime.now() } # Stop webdriver and return data browser.quit() return data def mars_news(browser): # Scrape Mars News # Visit the mars nasa news site url = 'https://data-class-mars.s3.amazonaws.com/Mars/index.html' browser.visit(url) # Optional delay for loading the page browser.is_element_present_by_css('div.list_text', wait_time=1) # Convert the browser html to a soup object and then quit the browser html = browser.html news_soup = soup(html, 'html.parser') # Add try/except for error handling try: slide_elem = news_soup.select_one('div.list_text') # Use the parent element to find the first 'a' tag and save it as 'news_title' news_title = slide_elem.find('div', class_='content_title').get_text() # Use the parent element to find the paragraph text news_p = slide_elem.find('div', class_='article_teaser_body').get_text() except AttributeError: return None, None return news_title, news_p def featured_image(browser): # Visit URL url = 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html' browser.visit(url) # Find and click the full image button full_image_elem = browser.find_by_tag('button')[1] full_image_elem.click() # Parse the resulting html with soup html = browser.html img_soup = soup(html, 'html.parser') # Add try/except for error handling try: # Find the relative image url img_url_rel = img_soup.find('img', class_='fancybox-image').get('src') except AttributeError: return None # Use the base url to create an absolute url img_url = f'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/{img_url_rel}' return img_url def mars_facts(): # Add try/except for error handling try: # Use 'read_html' to scrape the facts table into a dataframe df = pd.read_html('https://data-class-mars-facts.s3.amazonaws.com/Mars_Facts/index.html')[0] except BaseException: return None # Assign columns and set index of dataframe df.columns=['Description', 'Mars', 'Earth'] df.set_index('Description', inplace=True) # Convert dataframe into HTML format, add bootstrap return df.to_html(classes="table table-striped") ###### Deliverable 2 ####### def mars_hemispheres(browser): url = 'https://marshemispheres.com/' browser.visit(url) # 2. Create a list to hold the images and titles. linkName = [] linkImg = [] linkBare= [] hemisphere_image_urls = [] mars_image_url = "https://data-class-mars-hemisphere.s3.amazonaws.com/Mars_Hemispheres/" # 3. Write code to retrieve the image urls and titles for each hemisphere. # Optional delay for loading the page browser.is_element_not_present_by_css("div.item", wait_time = 1) # Convert the browser html to a soup object and then quit the browser html = browser.html head_soup = soup(html, "html.parser") slide_element = head_soup.select("div.item") # Use the parent element to find the first all titles and urls for item in slide_element: linkName.append(item.find("h3").get_text()) # finding img URLS for a in item.find_all("a", href=True): if a.text: linkImg.append(url + a["href"]) for link in linkImg: browser.visit(link) time.sleep(1) """ inner_soup = soup(browser.html, "html.parser") inner_element = inner_soup.select("div.downloads") for items in inner_element: img_url = items.find(href=True) hemisphere_image_urls.append(mars_image_url + img_url["href"]) """ # Find 'Sample' Image urls: img_url = browser.links.find_by_text("Sample") hemisphere_image_urls.append(img_url["href"]) #home page browser.visit(url) #making a dictionary for the links and titles hemisphere_image_urls = [{"img_url": hemisphere_image_urls, "title": linkName} for hemisphere_image_urls,linkName in zip(hemisphere_image_urls,linkName)] return hemisphere_image_urls if __name__ == "__main__": # If running as script, print scraped data print(scrape_all())
// #include <userver/formats/bson/value_builder.hpp> #include <userver/utest/utest.hpp> #include <agl/core/executer_state.hpp> #include <agl/core/operators-registry.hpp> #include <agl/core/variant.hpp> #include <agl/core/variant/parser.hpp> #include <agl/modules/manager.hpp> #include "core/default_operators_registry.hpp" namespace agl::core::variant::test { static const OperatorsRegistry kDefaultRegistry = [] { OperatorsRegistry r; r.RegisterOperators(GetDefaultOperatorsList()); return r; }(); static const ::agl::modules::Manager kEmptyModulesManager = [] { return ::agl::modules::Manager(kDefaultRegistry); }(); static const YamlParser::Deps kEmptyDeps(kDefaultRegistry, kEmptyModulesManager); Variant EvaluateFromString(const formats::yaml::Value& ast, const OperatorsRegistry& r, const YamlParser::Deps& deps) { const auto& parser = agl::core::variant::GetYamlParser("array", r); agl::core::Variant executable = parser.Parse(ast, deps); // execute the operator ExecuterState executer_state; agl::core::Variant result = executable.Evaluate(executer_state); EXPECT_TRUE(result.IsConstant()); EXPECT_FALSE(result.IsNone()); // check the result EXPECT_NO_THROW(result.AsList()); return result; } TEST(TestOperator, Coalesce) { auto ast = formats::yaml::FromString(R"( - value#coalesce: - value#integer: 1 - value#coalesce: - value#null: {} - value#integer: 1 - value#coalesce: - value#null: - value#integer: 1 - value#coalesce: - value#null: - value#null: {} )"); auto result = EvaluateFromString(ast, kDefaultRegistry, kEmptyDeps); agl::core::Variant::List result_list = result.AsList(); EXPECT_EQ(result_list.Size(), 4); EXPECT_EQ(result_list.Get<int64_t>(0), 1); EXPECT_EQ(result_list.Get<int64_t>(1), 1); EXPECT_EQ(result_list.Get<int64_t>(2), 1); EXPECT_TRUE(result_list.IsNone(3)); } namespace { const formats::json::Value foo_bar_json = [] { formats::json::ValueBuilder builder; builder["foo"] = "bar"; return builder.ExtractValue(); }(); class YamlParserJson : public YamlParserBase<YamlParserJson> { public: template <typename T> static void EnsureOperandsValid(T&&, const Deps&) {} template <typename T> static Variant ParseImpl(const T& operands, const Deps&) { if (operands.template As<std::string>() == "nullJson") { return formats::json::ValueBuilder(formats::json::Type::kNull) .ExtractValue(); } else if (operands.template As<std::string>() == "missJson") { return formats::json::Value()["missing"]; } else if (operands.template As<std::string>() == "foobar") { return foo_bar_json; } return Variant(); } }; class YamlParserBson : public YamlParserBase<YamlParserBson> { public: template <typename T> static void EnsureOperandsValid(T&&, const Deps&) {} template <typename T> static Variant ParseImpl(const T& operands, const Deps&) { if (operands.template As<std::string>() == "nullBson") { return formats::bson::ValueBuilder(formats::common::Type::kNull) .ExtractValue(); } else if (operands.template As<std::string>() == "missBson") { return formats::bson::Value()["missing"]; } return Variant(); } }; } // namespace TEST(TestOperator, CoalesceNullJson) { OperatorsRegistry r; r.RegisterOperators(GetDefaultOperatorsList()); r.RegisterOperators({{"json", std::make_shared<YamlParserJson>()}}); YamlParser::Deps deps(r, kEmptyModulesManager); auto ast = formats::yaml::FromString(R"( - value#coalesce: - value#json: nullJson - value#integer: 1 - value#coalesce: - value#json: nullJson inspect-value: false - value#integer: 1 - value#coalesce: - value#json: nullJson inspect-value: true - value#integer: 1 - value#coalesce: - value#json: missJson inspect-value: false - value#integer: 1 - value#coalesce: - value#json: missJson inspect-value: true - value#integer: 1 - value#coalesce: - value#json: nullJson inspect-value: true - value#json: missJson inspect-value: true - value#coalesce: - value#json: foobar - value#integer: 1 )"); auto result = EvaluateFromString(ast, r, deps); agl::core::Variant::List result_list = result.AsList(); EXPECT_EQ(result_list.Size(), 7); EXPECT_TRUE(result_list.Get<agl::core::variant::io::JsonPromise>(0) .AsJson() .IsNull()); EXPECT_TRUE(result_list.Get<agl::core::variant::io::JsonPromise>(1) .AsJson() .IsNull()); EXPECT_EQ(result_list.Get<int64_t>(2), 1); EXPECT_TRUE(result_list.Get<agl::core::variant::io::JsonPromise>(3) .AsJson() .IsMissing()); EXPECT_EQ(result_list.Get<int64_t>(4), 1); EXPECT_TRUE(result_list.IsNone(5)); EXPECT_EQ(result_list.Get<agl::core::variant::io::JsonPromise>(6).AsJson(), foo_bar_json); } TEST(TestOperator, CoalesceNullBson) { OperatorsRegistry r; r.RegisterOperators(GetDefaultOperatorsList()); r.RegisterOperators({{"bson", std::make_shared<YamlParserBson>()}}); YamlParser::Deps deps(r, kEmptyModulesManager); auto ast = formats::yaml::FromString(R"( - value#coalesce: - value#bson: nullBson - value#integer: 1 - value#coalesce: - value#bson: nullBson inspect-value: false - value#integer: 1 - value#coalesce: - value#bson: nullBson inspect-value: true - value#integer: 1 - value#coalesce: - value#bson: missBson inspect-value: false - value#integer: 1 - value#coalesce: - value#bson: missBson inspect-value: true - value#integer: 1 - value#coalesce: - value#bson: nullBson inspect-value: true - value#bson: missBson inspect-value: true )"); auto result = EvaluateFromString(ast, r, deps); agl::core::Variant::List result_list = result.AsList(); EXPECT_EQ(result_list.Size(), 6); EXPECT_TRUE(result_list.Get<variant::io::BsonPromise>(0).AsBson().IsNull()); EXPECT_TRUE(result_list.Get<variant::io::BsonPromise>(1).AsBson().IsNull()); EXPECT_EQ(result_list.Get<int64_t>(2), 1); EXPECT_TRUE( result_list.Get<variant::io::BsonPromise>(3).AsBson().IsMissing()); EXPECT_EQ(result_list.Get<int64_t>(4), 1); EXPECT_TRUE(result_list.IsNone(5)); } } // namespace agl::core::variant::test
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { catchError, map, of, Subscription } from 'rxjs'; import { GetLanguageEnum } from 'src/app/enums/LanguageEnum'; import { AppStateService } from 'src/app/services/app-state.service'; import { Router } from '@angular/router'; import { League } from 'src/app/models/League.model'; import { LeagueContactAddService } from './league-contact-add.service'; import { LeagueContact } from '../models/LeagueContact.model'; import { HighlightSpanKind } from 'typescript'; import { DemoDataService } from './demo-data.service'; import { ChartGamesPlayedService } from './chart-games-played.service'; @Injectable({ providedIn: 'root' }) export class LeagueAddService { AddingNewLeague: string[] = ['Adding new league', 'L\'ajout d\'une nouvelle ligue en cour']; Cancel: string[] = ['Cancel', 'Annuler']; Example: string[] = ['Example', 'Exemple']; LeagueIDIsRequired: string[] = ['League ID is required', 'L\'identité de ligue est requis']; LeagueAddSuccessful: string[] = ['League added successful', 'L\'ajout de la ligue réussie']; LeagueAddTxt: string[] = ['Add league', 'Ajoute une ligue']; LeagueName: string[] = ['League name', 'Nom de la ligue']; LeagueNameAlreadyExist: string[] = ['League name already exist', 'Nom de la ligue existe déjà']; LeagueNameIsRequired: string[] = ['League name is required', 'Nom de la ligue est requis']; PercentPointsFactor: string[] = ['Percent points factor', 'Facteur pourcentage points']; PercentPointsFactorIsRequired: string[] = ['Percent points factor is required', 'Facteur pourcentage points est requis']; PlayerLevelFactor: string[] = ['Player level factor', 'Facteur niveau du joueur']; PlayerLevelFactorIsRequired: string[] = ['Player level factor is required', 'Facteur niveau du joueur est requis']; PointsToLosers: string[] = ['Points to losers', 'Points aux perdants'] PointsToLosersIsRequired: string[] = ['Points to losers is required', 'Points aux perdants est requis'] PointsToWinners: string[] = ['Points to winners', 'Points aux gagnants'] PointsToWinnersIsRequired: string[] = ['Points to winners is required', 'Points aux gagnants est requis'] PleaseEnterRequiredInformation: string[] = ['Please enter required information', 'SVP entrer l\'information requise']; required: string[] = ['required', 'requis']; ReturnToHomePage: string[] = ['Return to home page', 'Retour à la page d\'accueil']; Status: string = ''; Working: boolean = false; Error: HttpErrorResponse = <HttpErrorResponse>{}; LeagueAddSuccess: boolean = false; private sub: Subscription = new Subscription(); constructor(public state: AppStateService, public httpClient: HttpClient, public router: Router, public leagueContactAddService: LeagueContactAddService, public demoDataService: DemoDataService, public chartGamesPlayedService: ChartGamesPlayedService) { } LeagueAdd(league: League) { if (this.state.DemoVisible) { for (let i = 0, count = this.state.LeagueList.length; i < count; i++) { if (this.state.LeagueList[i].LeagueName == league.LeagueName) { this.Error = <HttpErrorResponse>{ message: this.LeagueNameAlreadyExist[this.state.LangID] } return; } } let maxLeagueID: number = 0; for (let i = 0, count = this.state.LeagueList.length; i < count; i++) { if (maxLeagueID < this.state.LeagueList[i].LeagueID) { maxLeagueID = this.state.LeagueList[i].LeagueID; } } league.LeagueID = maxLeagueID + 1; this.state.LeagueList.push(league); this.state.DemoLeagueID = league.LeagueID; let leagueContact: LeagueContact = <LeagueContact>{ LeagueContactID: 1, LeagueID: league.LeagueID, ContactID: this.state.DemoUser.ContactID, IsLeagueAdmin: true, Active: true, PlayingToday: true, Removed: false, }; this.state.LeagueContactList = []; this.state.LeagueContactList.push(leagueContact); this.state.GameList = []; this.state.PlayerGameModelList = []; this.state.PlayerList = []; this.state.PlayerList.push(this.state.DemoUser) this.state.DatePlayerStatModelList = []; this.state.CurrentDatePlayerStatModelList = []; this.state.CurrentPlayerDateID = 0; this.demoDataService.GenerateDemoDataDemoExtraPlayerList(); this.chartGamesPlayedService.DrawGamesPlayedChart(); return; } else { this.Status = `${this.AddingNewLeague[this.state.LangID]} - ${league.LeagueName}`; this.Working = true; this.Error = <HttpErrorResponse>{}; this.sub ? this.sub.unsubscribe() : null; this.sub = this.DoLeagueAdd(league).subscribe(); } } GetErrorMessage(fieldName: 'LeagueID' | 'LeagueName' | 'PointsToWinners' | 'PointsToLosers' | 'PlayerLevelFactor' | 'PercentPointsFactor', form: FormGroup): string { switch (fieldName) { case 'LeagueID': { if (form.controls[fieldName].hasError('required')) { return this.LeagueIDIsRequired[this.state.LangID]; } return ''; } case 'LeagueName': { if (form.controls[fieldName].hasError('required')) { return this.LeagueNameIsRequired[this.state.LangID]; } return ''; } case 'PointsToWinners': { if (form.controls[fieldName].hasError('required')) { return this.PointsToWinnersIsRequired[this.state.LangID]; } return ''; } case 'PointsToLosers': { if (form.controls[fieldName].hasError('required')) { return this.PointsToLosersIsRequired[this.state.LangID]; } return ''; } case 'PlayerLevelFactor': { if (form.controls[fieldName].hasError('required')) { return this.PlayerLevelFactorIsRequired[this.state.LangID]; } return ''; } case 'PercentPointsFactor': { if (form.controls[fieldName].hasError('required')) { return this.PercentPointsFactorIsRequired[this.state.LangID]; } return ''; } default: return ''; } } GetFormValid(form: FormGroup): boolean { return form.valid ? true : false; } GetHasError(fieldName: 'LeagueID' | 'LeagueName' | 'PointsToWinners' | 'PointsToLosers' | 'PlayerLevelFactor' | 'PercentPointsFactor', form: FormGroup): boolean { return this.GetErrorMessage(fieldName, form) == '' ? false : true; } ResetLocals() { this.Status = ''; this.Working = false; this.Error = <HttpErrorResponse>{}; this.LeagueAddSuccess = false; } SubmitLeagueAddForm(form: FormGroup) { if (form.valid) { let league: League = <League>{ LeagueID: form.controls['LeagueID'].value, LeagueName: form.controls['LeagueName'].value, PointsToWinners: form.controls['PointsToWinners'].value, PointsToLosers: form.controls['PointsToLosers'].value, PlayerLevelFactor: form.controls['PlayerLevelFactor'].value, PercentPointsFactor: form.controls['PercentPointsFactor'].value, }; this.LeagueAdd(league); } } private DoLeagueAdd(league: League) { let languageEnum = GetLanguageEnum(); const url: string = `${this.state.BaseApiUrl}${languageEnum[this.state.Language]}-CA/league`; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.state.User.Token}`, }) }; return this.httpClient.post<League>(url, JSON.stringify(league), httpOptions) .pipe(map((x: any) => { this.DoUpdateForLeagueAdd(x); }), catchError(e => of(e).pipe(map(e => { this.DoErrorForLeagueAdd(e); })))); } private DoUpdateForLeagueAdd(league: League) { this.Status = ''; this.Working = false; this.Error = <HttpErrorResponse>{}; this.LeagueAddSuccess = true; this.state.LeagueID = league.LeagueID; let leagueContact: LeagueContact = <LeagueContact>{ LeagueContactID: 0, LeagueID: league.LeagueID, ContactID: this.state.DemoVisible ? this.state.DemoUser.ContactID : this.state.User.ContactID, IsLeagueAdmin: true, Active: true, PlayingToday: true }; this.leagueContactAddService.LeagueContactAdd(leagueContact); console.debug(league); } private DoErrorForLeagueAdd(e: HttpErrorResponse) { this.Status = ''; this.Working = false; this.Error = <HttpErrorResponse>e; this.LeagueAddSuccess = false; console.debug(e); } }
package com.newaim.purchase.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import java.util.Locale; /** * 国际化语言支持 * Created by Mark on 2017/9/6. */ @Configuration public class LocaleConfig extends WebMvcConfigurerAdapter{ @Bean public MessageSource messageSource(){ ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("i18n/messages"); return messageSource; } @Bean public LocaleResolver localeResolver(){ SessionLocaleResolver localeResolver = new SessionLocaleResolver(); //默认语言 localeResolver.setDefaultLocale(Locale.US); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); //参数名 localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
import { Disease } from "@/lib/data"; import { List, ListItem, SubHeading } from "@/pages/disease/[id]"; interface ClassificationProps { disease: Disease; } export default function Diagnosis({ disease }: ClassificationProps) { return ( <> {disease.diagnosis && ( <ListItem> <SubHeading>Diagnose:</SubHeading> <List> {Array.isArray(disease.diagnosis) ? ( disease.diagnosis.map((diagnosisItem: string, index: number) => ( <ListItem key={`diagnosis_${index}`}> <label> {diagnosisItem} <input type="checkbox" /> </label> </ListItem> )) ) : ( <> {disease.diagnosis.blood && ( <> <ListItem> <SubHeading>Blut:</SubHeading> <List> {disease.diagnosis.blood.map( (bloodDiagnosis: string, index: number) => ( <ListItem key={`blood_${index}`}> <label> {bloodDiagnosis} <input type="checkbox" /> </label> </ListItem> ) )} </List> </ListItem> </> )} {disease.diagnosis.urine && ( <> <ListItem> <SubHeading>Urin:</SubHeading> <List> {disease.diagnosis.urine.map( (urineDiagnosis: string, index: number) => ( <ListItem key={`urine_${index}`}> <label> {urineDiagnosis} <input type="checkbox" /> </label> </ListItem> ) )} </List> </ListItem> </> )} </> )} </List> </ListItem> )} </> ); }
package ru.netology.nmedia.viewModel import android.net.Uri import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import ru.netology.nmedia.auth.AppAuth import ru.netology.nmedia.model.PhotoModel import ru.netology.nmedia.util.SingleLiveEvent import java.io.File import javax.inject.Inject @HiltViewModel class SignUpViewModel @Inject constructor (private val appAuth: AppAuth): ViewModel() { private val dataAuth = appAuth private val _response = SingleLiveEvent<Unit>() val response: LiveData<Unit> = _response private val _error = SingleLiveEvent<Unit>() val error: LiveData<Unit> = _error fun registerAndSetAuth(login: String, password: String, name: String) = viewModelScope.launch { try { val user = dataAuth.registerUser(login, password, name) user.token?.let { dataAuth.setAuth(user.id, it) } _response.value = Unit } catch (e: Exception) { _error.value = Unit } } private val _photo = MutableLiveData<PhotoModel?>(null) val photo: LiveData<PhotoModel?> get() = _photo fun setPhoto(uri: Uri, file: File) { //это первая часть сохранения, 2 часть - в функции registerWithAvatarAndSetAuth (читаем инфо из значения photo) _photo.value = PhotoModel(uri, file) } fun clearPhoto() { _photo.value = null } fun registerWithAvatarAndSetAuth(login: String, password: String, name: String) = viewModelScope.launch { try { val photoModel = _photo.value //читаем из _photo значение, 2 часть сохранения if (photoModel == null) { val user = dataAuth.registerUser(login, password, name) user.token?.let { dataAuth.setAuth(user.id, it) } _response.value = Unit } else { val user = dataAuth.registerUserWithAvatar(login, password, name, photoModel.file) user.token?.let { dataAuth.setAuth(user.id, it) } _response.value = Unit } } catch (e: Exception) { _error.value = Unit } } }
import os import unittest import pandas as pd from pathlib import Path import pickle import numpy as np import warnings warnings.filterwarnings("ignore") from kmdcm.pydcm.dcm import ( mdcm_set_up, eval_kernel, ) from kmdcm.pydcm.dcm import FFE_PATH, espform, densform from kmdcm.utils import dcm_utils as du from kmdcm.pydcm.mdcm_dict import MDCM from kmdcm.pydcm.kernel import KernelFit def make_df_same_size(df_dict): """ Pad all dataframes in a dictionary to the same size :param df_dict: :return: """ sizes = { k: 1 if type(df_dict[k]) is not list else len(df_dict[k]) for k in df_dict.keys() } max_size = max(sizes.values()) for k in df_dict.keys(): if sizes[k] < max_size: df_dict[k] = np.pad(df_dict[k], (0, max_size - sizes[k]), "constant") return df_dict # path to this file PATH_TO_TESTDIR = Path(os.path.dirname(os.path.abspath(__file__))) import re def clean_non_alpha(x): x = re.sub("[^0-9]", "", x) return int(x) def ignore_warnings(test_func): def do_test(self, *args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore", ResourceWarning) test_func(self, *args, **kwargs) return do_test class kMDCM_Experiments(unittest.TestCase): """ Class of tests and experiments for kMDCM """ def get_mdcm(self, mdcm_dict=None): if mdcm_dict is not None and type(mdcm_dict) is dict: if "scan_fesp" in mdcm_dict.keys(): scan_fesp = mdcm_dict["scan_fesp"] else: scan_fesp = None if "scan_fdns" in mdcm_dict.keys(): scan_fdns = mdcm_dict["scan_fdns"] else: scan_fdns = None if "mdcm_cxyz" in mdcm_dict.keys(): mdcm_cxyz = mdcm_dict["mdcm_cxyz"] else: mdcm_cxyz = None if "mdcm_clcl" in mdcm_dict.keys(): mdcm_clcl = mdcm_dict["mdcm_clcl"] else: mdcm_clcl = None if "local_pos" in mdcm_dict.keys(): local_pos = mdcm_dict["local_pos"] else: local_pos = None else: scan_fesp = None scan_fdns = None local_pos = None mdcm_cxyz = None mdcm_clcl = None if scan_fesp is None: scan_fesp = [espform] if scan_fdns is None: scan_fdns = [densform] return mdcm_set_up( scan_fesp, scan_fdns, local_pos=local_pos, mdcm_cxyz=mdcm_cxyz, mdcm_clcl=mdcm_clcl, ) def test_load_data( self, l2, cube_path=None, pickle_path=None, natoms=5, uuid=None, fname=None, ): print("Cube path:", cube_path) print("Pickle path:", pickle_path) print(f"Loading data, uuid:{uuid}") if cube_path is None: cube_path = f"{FFE_PATH}/cubes/dcm/" if pickle_path is None: PICKLES = list(Path(f"{FFE_PATH}/cubes/clcl/{l2}").glob("*clcl.obj")) else: PICKLES = list(Path(pickle_path).glob("*")) scanpath = Path(cube_path) chosen_points = [] chosen_files = [] for c in scanpath.glob("*.p.cube"): ccode = c.name.split(".p.")[0] if ccode not in chosen_points: chosen_points.append(ccode) chosen_files.append(c) CUBES = [ scanpath / f"{chosen_files[i].parents[0]}/{c}.p.cube" for i, c in enumerate(chosen_points) ] # make the cube and pickle lists the same, keeping the order based on # the cube list pkls = [] # print("PICKLES:", PICKLES) for _ in chosen_points: tmp_pkl = [x for x in PICKLES if str(Path(_).stem).split(".")[0] == str(x.stem).split(".")[0]] #print(tmp_pkl) pkls.append(tmp_pkl[0]) PICKLES = pkls # they must be the same length assert len(CUBES) == len(PICKLES) assert len(CUBES) > 0 # sort them import re def clean_non_alpha(x): #print(x) x = re.sub("[^0-9]", "", x) #print(x) return int(x) CUBES.sort(key=lambda x: clean_non_alpha(str(x.stem).split(".")[0])) PICKLES.sort(key=lambda x: clean_non_alpha(str(x.stem).split(".")[0])) for i in range(len(CUBES)): #print(i, CUBES[i].stem, PICKLES[i].stem) assert clean_non_alpha(str(CUBES[i].stem).split(".")[0]) == clean_non_alpha( str(PICKLES[i].stem).split(".")[0]), f"{CUBES[i].stem} {PICKLES[i].stem}" # return the data return du.get_data(CUBES, PICKLES, natoms) def test_standard_rmse( self, files, cubes, pickles, cubes_pwd=None, fname="", mdcm_dict=None, ): """ Test the standard RMSE :param files: list of CLCL filenames :param cubes: list of cube objects :param pickles: list of pickle objects :param cubes_pwd: path to the cubes :return: """ rmses = eval_kernel( files, cubes, cubes, fname=fname, mdcm_clcl=mdcm_dict["mdcm_clcl"], mdcm_xyz=mdcm_dict["mdcm_cxyz"], ) # print("RMSEs:", rmses) rmse = sum(rmses) / len(rmses) print("RMSE:", rmse) pd.DataFrame({"rmses": rmses, "filename": files}).to_csv( f"{fname}_standard_.csv" ) def test_N_repeats(self, n=1): for i in range(n): print("i", i) self.experiments() @ignore_warnings def test_fit( self, alpha=0.0, l2=0.0, do_null=False, n_factor=2, do_optimize=False, cubes_pwd=FFE_PATH / "cubes/dcm/", mdcm_dict=None, load_data=False, fname="test", natoms=3, uuid=None, ): """ Test the kernel fit """ if mdcm_dict is None: # path to cubes cube_paths = Path(cubes_pwd) ecube_files = list(cube_paths.glob("*/.cube")) dcube_files = list(cube_paths.glob("*/*dens.cube")) elif isinstance(mdcm_dict, str): mdcm_dict = MDCM(mdcm_dict).asDict() else: mdcm_dict = mdcm_dict.asDict() if isinstance(mdcm_dict, dict): print("mdcm_dict") ecube_files = mdcm_dict["scan_fesp"] dcube_files = mdcm_dict["scan_fdns"] mdcm_dict["scan_fesp"] = [mdcm_dict["scan_fesp"][0]] mdcm_dict["scan_fdns"] = [mdcm_dict["scan_fdns"][0]] # load mdcm object m = self.get_mdcm(mdcm_dict=mdcm_dict) # kernel fit k = KernelFit() # dp optimization if do_optimize and uuid is None: ecube_files = sorted(ecube_files, key=lambda x: clean_non_alpha( str(Path(x).stem).split(".")[0])) dcube_files = sorted(dcube_files, key=lambda x: clean_non_alpha( str(Path(x).stem).split(".")[0])) print("*" * 80) print("Optimizing with l2=", l2) opt_rmses = eval_kernel( None, ecube_files, dcube_files, opt=True, l2=l2, fname=fname, uuid=k.uuid, mdcm_clcl=mdcm_dict["mdcm_clcl"], mdcm_xyz=mdcm_dict["mdcm_cxyz"], ) # print("Opt RMSEs:", opt_rmses) opt_rmse = sum(opt_rmses) / len(opt_rmses) print("Opt RMSE:", opt_rmse) # unload the data x, i, y, cubes, pickles = self.test_load_data( l2=str(l2), pickle_path=FFE_PATH / "cubes" / "clcl" / fname / f"{k.uuid}", cube_path=FFE_PATH / "cubes" / fname, natoms=natoms, ) pickles = sorted(pickles, key=lambda x: clean_non_alpha( str(Path(x).stem).split(".")[0])) if uuid is not None: # k = pd.read_pickle() # unload the data x, i, y, cubes, pickles = self.test_load_data( l2=str(l2), pickle_path=FFE_PATH / "cubes" / "clcl" / fname / f"{uuid}", cube_path=FFE_PATH / "cubes" / fname, natoms=natoms, uuid=uuid, fname=fname ) # CUBES.sort(key=lambda x: clean_non_alpha(str(x.stem))) pickles = sorted(pickles, key=lambda x: clean_non_alpha( str(Path(x).stem).split(".")[0])) ecube_files = sorted(ecube_files, key=lambda x: clean_non_alpha( str(Path(x).stem).split(".")[0])) dcube_files = sorted(dcube_files, key=lambda x: clean_non_alpha( str(Path(x).stem).split(".")[0])) if do_optimize: print("doing opt::") # optimized model opt_rmses = eval_kernel( pickles, ecube_files, dcube_files, load_pkl=True, mdcm_clcl=mdcm_dict["mdcm_clcl"], mdcm_xyz=mdcm_dict["mdcm_cxyz"], uuid=uuid, opt=True, l2=l2, fname=fname, ) # print("Opt RMSEs:", opt_rmses) opt_rmse = sum(opt_rmses) / len(opt_rmses) print("Opt RMSE:", opt_rmse) # unload the data x, i, y, cubes, pickles = self.test_load_data( l2=str(l2), pickle_path=FFE_PATH / "cubes" / "clcl" / fname / f"{uuid}", cube_path=FFE_PATH / "cubes" / fname, natoms=natoms, ) uuid = k.uuid # all arrays should be the same length assert len(x) == len(i) == len(y) == len(cubes) == len(pickles) k.set_data(x, i, y, cubes, pickles, fname=fname) k.fit(alpha=alpha, N_factor=n_factor, l2=l2) # printing print("*" * 20, "Kernel Fit", "*" * 20) print("N X:", len(k.X)) print("N:", len(k.ids)) print("N test:", len(k.test_ids)) print("N_train:", len(k.train_ids)) print("r2s:", k.r2s) print("sum r2s test:", sum([_[0] for _ in k.r2s])) print("sum r2s train:", sum([_[1] for _ in k.r2s])) print("n models:", len(k.r2s)) # Move the local charges print("Moving clcls") files = k.move_clcls(m) print("N files:", len(files), "\n") print("*" * 20, "Eval Results", "*" * 20) # test the original model if do_null: print(" " * 20, "Eval Null", "*" * 20) self.test_standard_rmse( k, files, cubes, pickles, mdcm_dict=mdcm_dict, fname=fname ) # test the optimized model rmses = eval_kernel( files, ecube_files, dcube_files, load_pkl=True, mdcm_clcl=mdcm_dict["mdcm_clcl"], mdcm_xyz=mdcm_dict["mdcm_cxyz"], uuid=k.uuid, l2=l2, fname=fname, ) # Printing the rmses self.print_rmse(rmses) # print("RMSEs:", rmses) kern_df = self.prepare_df(k, rmses, files, alpha=alpha, l2=l2, fname=fname) print("test:", kern_df[kern_df["class"] == "test"]["rmse"].mean()) print("train:", kern_df[kern_df["class"] == "train"]["rmse"].mean()) if do_optimize is True: opt_df = self.prepare_df( k, opt_rmses, files, alpha=alpha, l2=l2, opt=True, fname=fname ) print("(opt) test:", opt_df[opt_df["class"] == "test"]["rmse"].mean()) print("(opt) train:", opt_df[opt_df["class"] == "train"]["rmse"].mean()) print("*" * 20, "Eval Kernel", "*" * 20) # pickle kernel self.pickle_kernel(k) # write manifest print("Writing manifest") k.write_manifest(PATH_TO_TESTDIR / f"manifest/{k.uuid}.json") return k def print_rmse(self, rmses): # print("RMSEs:", rmses) rmse = sum(rmses) / len(rmses) print("RMSE:", rmse) return rmse def prepare_df(self, k, rmses, files, alpha=0.0, l2=0.0, opt=False, fname="test"): """ """ class_name = ["test" if _ in k.test_ids else "train" for _ in k.ids] if opt: fn = f"csvs/{fname}_opt_{k.uuid}_{l2}.csv" else: fn = f"csvs/{fname}_kernel_{k.uuid}_{alpha}_{l2}.csv" df_dict = { "rmse": rmses, "pkl": files, "class": class_name, "alpha": alpha, "uuid": k.uuid, "l2": l2, "type": ["nms" if "nms" in str(_) else "scan" for _ in files], } df = pd.DataFrame(make_df_same_size(df_dict)) df.to_csv(fn) return df def pickle_kernel(self, k): p = PATH_TO_TESTDIR / f"models/kernel_{k.uuid}.pkl" print("Pickling kernel to", p) with open(p, "wb") as f: pickle.dump(k, f) if __name__ == "__main__": from argparse import ArgumentParser import argparse parser = argparse.ArgumentParser() parser.add_argument("--alpha", type=float, default=0.0) parser.add_argument("--n_factor", type=int, default=1) parser.add_argument("--n_atoms", type=int, default=6) parser.add_argument("--do_opt", action='store_true', default=False) parser.add_argument("--l2", type=float, default=0.0) parser.add_argument("--fname", type=str, default="test") parser.add_argument("--uuid", type=str, default=None) parser.add_argument("--json", type=str, required=True) parser.add_argument("unittest_args", nargs="*") args = parser.parse_args() print(args) k = kMDCM_Experiments() k.test_fit( alpha=args.alpha, n_factor=args.n_factor, natoms=args.n_atoms, l2=args.l2, fname=args.fname, mdcm_dict=args.json, do_optimize=args.do_opt, uuid=args.uuid, )
using System.Text; using System.Text.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Shared; namespace RabbitMQ.Consumer; public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); var factory = new ConnectionFactory { HostName = "localhost", UserName = "guest", Password = "guest" }; var queueName = "queueName"; using var connection = factory.CreateConnection(); using var channel = connection.CreateModel(); channel.QueueDeclare( //creating queue programmatically queue: queueName, durable: true, exclusive: false, autoDelete: false, arguments: null ); var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, eventArgs) => { var body = eventArgs.Body.ToArray(); var message = Encoding.UTF8.GetString(body); //TODO: add crypto to messages to increase security var order = JsonSerializer.Deserialize<Order>(message); _logger.LogInformation(order?.ToString()); }; channel.BasicConsume( queue: queueName, autoAck: true, //automatically remove message from queue when processed consumer: consumer ); await Task.Delay(5000, stoppingToken); } } }
package _08Generics._02Exercise._05GenericCountMethodString; import java.util.ArrayList; import java.util.List; public class Box<T extends Comparable<T>> { private List<T> values; private void checkIndex(int index) { if(index < 0 || index >= values.size()) { throw new IndexOutOfBoundsException(String.format("Index %s out of bounds for length %d", index, values.size())); } } public Box() { values = new ArrayList<>(); } public void add(T element) { values.add(element); } public T get(int index) { checkIndex(index); return values.get(index); } public void swap(int index1, int index2) { checkIndex(index1); checkIndex(index2); T firstElement = values.get(index1); T secondElement = values.get(index2); values.set(index1, secondElement); values.set(index2, firstElement); // Collections.swap(values, index1, index2); } @Override public String toString() { StringBuilder sb = new StringBuilder(); values.forEach(e -> sb.append(String.format("%s: %s%n", e.getClass().getName(), e))); return sb.toString(); } public int getGreaterCount(T comparingElement) { int count = (int) values.stream() .filter(e -> e.compareTo(comparingElement) > 0) .count(); return count; // int count = 0; // for (T value : values) { // if(value.compareTo(comparingElement) > 0) { // count++; // } // } // // return count; } }
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { ListResponseModel } from '../models/listResponseModel'; import { Car } from '../models/car'; import { environment } from 'src/environments/environment'; import { ResponseModel } from '../models/responseModel'; @Injectable({ providedIn: 'root' }) export class CarService { constructor(private httpClient: HttpClient) { } getCars():Observable<ListResponseModel<Car>> { let newPath =environment.apiUrl+"cars/getcardetail"; return this.httpClient.get<ListResponseModel<Car>>(newPath); } getCarImages():Observable<ListResponseModel<Car>> { let newPath =environment.apiUrl+"cars/getcarimagedetail"; return this.httpClient.get<ListResponseModel<Car>>(newPath); } getCarsByBrandId(brandId:number):Observable<ListResponseModel<Car>>{ let newPath =environment.apiUrl+"cars/getcarsbybrandid?brandId="+brandId; return this.httpClient.get<ListResponseModel<Car>>(newPath); } getCarsByColorId(colorId:number):Observable<ListResponseModel<Car>>{ let newPath =environment.apiUrl+"cars/getcarsbycolorid?colorId="+colorId; return this.httpClient.get<ListResponseModel<Car>>(newPath); } getCarsByBrandAndColor(colorId:number,brandId:number):Observable<ListResponseModel<Car>>{ let newPath = environment.apiUrl + 'cars/getcardetailsbybrandandcolorid?brandId='+ brandId +"&colorId=" + colorId; return this.httpClient.get<ListResponseModel<Car>>(newPath); } add(car:Car):Observable<ResponseModel>{ return this.httpClient.post<ResponseModel>(environment.apiUrl+"cars/add",car) } getCarDetail(carId:number):Observable<ListResponseModel<Car>>{ let newPath = environment.apiUrl + 'cars/getcardetail?carId='+carId return this.httpClient.get<ListResponseModel<Car>>(newPath) } }
import { task } from "@/hooks/useTask"; import { Pen, Trash2 } from "lucide-react"; import Icon from "./Icon"; import { useContext } from "react"; import { TaskContext } from "@/contexts/TaskContext"; export default function TaskDeatils({ task, i, nameTaskUpdate, setNameTaskUpdate, }: { i: number; task: task; nameTaskUpdate: string; setNameTaskUpdate: React.Dispatch<React.SetStateAction<string>>; }) { const { deleteTask, switchDone, updateNameTask } = useContext(TaskContext); return ( <div className="flex justify-between items-center" key={task._id}> <form className="flex gap-4 items-center" onSubmit={(e) => { e.preventDefault(); nameTaskUpdate.length > 0 && setNameTaskUpdate(""); updateNameTask(task._id, nameTaskUpdate); setNameTaskUpdate(""); let input = document.getElementById(task._id); input?.blur(); input.disabled = "true"; }} > <input type="checkbox" name={i.toString()} checked={task.done} id={i.toString()} onClick={() => { switchDone(task._id); }} /> <label htmlFor={i.toString()} onClick={() => { document.getElementById(i)?.focus(); }} > <input type="text" disabled={true} id={task._id} value={ nameTaskUpdate.length > 0 && document.getElementById(task._id)?.disabled === false ? nameTaskUpdate : task.name } onChange={(e) => setNameTaskUpdate(e.target.value)} className="text-white bg-black text-xl" /> </label> </form> <div className="flex gap-4 "> <Icon onClick={() => deleteTask(task._id)} color="red"> <Trash2 /> </Icon> <Icon onClick={() => { let input = document.getElementById(task._id); input?.removeAttribute("disabled"); setNameTaskUpdate(task.name); input?.focus(); }} color="sky" > <Pen /> </Icon> </div> </div> ); }
from pytest import raises from tft.main import TftAppTest def test_tft(): # test tft without any subcommands or arguments with TftAppTest() as app: app.run() assert app.exit_code == 0 def test_tft_debug(): # test that debug mode is functional argv = ['--debug'] with TftAppTest(argv=argv) as app: app.run() assert app.debug is True def test_command1(): # test command1 without arguments argv = ['command1'] with TftAppTest(argv=argv) as app: app.run() data,output = app.last_rendered assert data['foo'] == 'bar' assert output.find('Foo => bar') # test command1 with arguments argv = ['command1', '--foo', 'not-bar'] with TftAppTest(argv=argv) as app: app.run() data,output = app.last_rendered assert data['foo'] == 'not-bar' assert output.find('Foo => not-bar')
import { useState, useEffect } from "react"; import { Link, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { passportInstance, fetchAuth } from "../store/immutable"; export default function Toolbar({setTab}) { const [user, setUser] = useState(undefined) const navigate = useNavigate() const checkUserLoggedIn = async () => { const userProfile = await passportInstance.getUserInfo(); Boolean(userProfile !== undefined) && setUser(() => { setTab('game') navigate("/game") return { nickname: userProfile?.nickname, email: userProfile?.email, sub: userProfile?.sub, } }); }; useEffect(() => { checkUserLoggedIn(); }, []); const menuClick = async () => { await fetchAuth() && checkUserLoggedIn(); } const logOut = async () => { Boolean(user !== undefined) && await passportInstance.logout(); setTab('home') navigate('/') } const handleTabClick = (e) => { setTab(e.currentTarget.attributes.href.textContent) } return ( <div className="toolbar"> <Link to='game' onClick={handleTabClick}>Game</Link> <div className="logo" onClick={user === undefined ? menuClick : null}> <LogoLink to='game' className="logo-link" /> </div> <Link onClick={logOut} className="sb-login-link" data-team-name={user?.email ?? '-'}/> </div> ); } const LogoLink = styled(Link)` width: 100%; height: 100%; display: block; border: none; `
class WeatherData { final String cityName; final double temperature; final String description; final String main; final String icon; WeatherData({ required this.cityName, required this.temperature, required this.description, required this.main, required this.icon, }); factory WeatherData.fromJson(Map<String, dynamic> json) { return WeatherData( cityName: json['name'], temperature: json['main']['temp'].toDouble(), description: json['weather'][0]['description'], main: json['weather'][0]['main'], icon: json['weather'][0]['icon'] ); } }
import { HardhatRuntimeEnvironment } from "hardhat/types" import { DeployFunction } from "hardhat-deploy/types" import verify from "../utils/helper-functions"; import { networkConfig, developmentChains } from "../utils/helper-constants"; import { ethers } from "hardhat" const deployCowriesToken: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { // @ts-ignore const { getNamedAccounts, deployments, network } = hre const { deploy, log } = deployments const { deployer } = await getNamedAccounts() log("----------------------------------------------------") log("Deploying CowriesToken and waiting for confirmations...") const cowriesToken = await deploy("CowriesToken", { from: deployer, args: [], log: true, // we need to wait if on a live network so we can verify properly waitConfirmations: networkConfig[network.name].blockConfirmations || 1, }) log(`CowriesToken at ${cowriesToken.address}`) if (!developmentChains.includes(network.name) && process.env.ETHERSCAN_API_KEY) { await verify(cowriesToken.address, []) } log(`Delegating to ${deployer}`) await delegate(cowriesToken.address, deployer) log("Delegated!") } const delegate = async (cowriesTokenAddress: string, delegatedAccount: string) => { const cowriesToken = await ethers.getContractAt("CowriesToken", cowriesTokenAddress) const transactionResponse = await cowriesToken.delegate(delegatedAccount) await transactionResponse.wait(1) console.log(`Checkpoints: ${await cowriesToken.numCheckpoints(delegatedAccount)}`) } export default deployCowriesToken deployCowriesToken.tags = ["all", "villagesquare"]
import { EventEmitter } from '@angular/core'; import { SocketReadyState } from './socket.enum'; export class SocketSimple<T> { private _socket: WebSocket; private _url: string; public get isConnected(): boolean { return this._socket && this._socket.readyState === SocketReadyState.Open; } public received = new EventEmitter<T>(); public rawReceived = new EventEmitter<string>(); public opened = new EventEmitter<boolean>(); public closed = new EventEmitter<boolean>(); constructor(url: string) { this._url = url; } public connect() { this._socket = new WebSocket(this._url); this._socket.onopen = (event: Event) => this.onOpen(event); this._socket.onerror = (event: Event) => this.onError(event); this._socket.onmessage = (message: MessageEvent) => this.onReceived(message); } public send(message: T) { if (!this._socket) { return; } this._socket.send(JSON.stringify(message)); } public disconnect(): boolean { if (!this._socket) { return false; } this._socket.close(); this.closed.emit(this.isConnected); } public onOpen(event: Event) { console.log(event); this.opened.emit(this.isConnected); } public onReceived(message: any) { this.rawReceived.emit(message); this.received.emit(this.stringToJsObject(message)); } public onError(error: Event) { switch (error.type) { case 'close': break; default: console.log('error', error); break; } this.disconnect(); } private stringToJsObject(str: string): T { if (!str) { return null; } try { if (str.startsWith('{') || str.startsWith('[')) { return JSON.parse(str); } } catch (error) { console.log(error); } } }
'use client'; import React, { useState } from 'react'; import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; import { app } from '../../../config/firebase'; const LoginForm = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const handleLogin = async (e: { preventDefault: () => void; }) => { e.preventDefault(); const auth = getAuth(app); try { await signInWithEmailAndPassword(auth, email, password); setError(''); window.location.href = '/'; } catch (error: any) { setError(error.message); alert(error.message) } }; return ( <div className="login-form"> <h1>Login</h1> <form onSubmit={handleLogin}> <label>Email:</label> <input type="email" placeholder="Enter your email" value={email} onChange={(e) => setEmail(e.target.value)} /> <label>Password:</label> <input type="password" placeholder="Enter your password" value={password} onChange={(e) => setPassword(e.target.value)} /> {error && <p className="error-message">{error}</p>} <button type="submit">Login</button> </form> </div> ); }; export default LoginForm;
import React, {useState, useEffect} from 'react'; import {View} from 'react-native'; import R from '@components/utils/R'; import moment from 'moment'; import {useUpdateScheduleMutation} from '@store/services/userApiSlice'; import Text from '@components/common/Text'; import ScreenBoiler from '@components/layout/header/ScreenBoiler'; import Button from '@components/common/Button'; import TimeDatePicker from '@components/common/TimeDatePicker'; import DropDown from '@components/common/DropDown'; import {daysOfWeek} from '@components/constants/companyData'; import TextInput from '@components/common/TextInput'; import FormScrollContainer from '@components/view/screens/FormScrollContainer'; import PopUp from '@components/common/PopUp'; import FormValidation from '@components/utils/FormValidation'; function EditScheduleScreen(props) { const {navigation} = props; const {item} = props.route.params; const [updateSchedule] = useUpdateScheduleMutation(); const [isLoading, setIsLoading] = useState(false); const [scheduleData, setScheduleData] = useState({ day: '', startDate: '', endDate: '', noOfWeeks: '', startTime: '', finishTime: '', sessionType: '', notes: '', address: '', staffNotes: '', }); const [errorField, setErrorField] = useState({ day: '', startDate: '', endDate: '', noOfWeeks: '', startTime: '', finishTime: '', sessionType: '', notes: '', address: '', staffNotes: '', }); useEffect(() => { for (let key in item) { if (key in scheduleData) { if (key === 'startTime' || key === 'finishTime') { setScheduleData(prevState => ({ ...prevState, [key]: moment(item[key], 'HH:mm:ss'), })); } else { setScheduleData(prevState => ({...prevState, [key]: item[key]})); } } } }, [item]); const onSubmit = () => { setIsLoading(true); const formError = FormValidation(scheduleData); if (formError) { setIsLoading(false); const obj = {}; formError?.errorArr?.map(item => { obj[item] = formError?.message; }); setErrorField({ ...{ day: '', startDate: '', endDate: '', noOfWeeks: '', startTime: '', finishTime: '', sessionType: '', notes: '', address: '', staffNotes: '', }, ...obj, }); } else if ( Number( moment(scheduleData?.endDate).diff( moment(scheduleData?.startDate), 'days', ), ) < 0 ) { setIsLoading(false); PopUp({ heading: 'End Date should be greater than start date', position: 'top', popupType: 'danger', }); return; } else if ( Number( moment(scheduleData?.finishTime).diff( moment(scheduleData?.startTime), 'minutes', ), ) < 0 ) { setIsLoading(false); PopUp({ heading: 'End Time should be greater than start time', position: 'top', popupType: 'danger', }); return; } else { setIsLoading(true); setErrorField({ day: '', startDate: '', endDate: '', noOfWeeks: '', startTime: '', finishTime: '', sessionType: '', notes: '', address: '', staffNotes: '', }); const reqData = { ...scheduleData, scheduleId: item?._id, startDate: moment(scheduleData?.startDate).format('MM/DD/YYYY'), startTime: moment(scheduleData?.startTime).format('hh:mm a'), endDate: moment(scheduleData?.endDate).format('MM/DD/YYYY'), finishTime: moment(scheduleData?.finishTime).format('hh:mm a'), noOfWeeks: Number(scheduleData?.noOfWeeks), }; updateSchedule(reqData) .unwrap() .then(res => { PopUp({ heading: 'Schedule Updated Successfully', bottomOffset: 0.7, visibilityTime: 3000, position: 'top', popupType: 'sucess', }); navigation.goBack(); setIsLoading(false); }) .catch(err => { PopUp({ heading: err?.data?.message?.error[0] || 'Something went wrong', bottomOffset: 0.7, visibilityTime: 3000, position: 'top', popupType: 'danger', }); setIsLoading(false); }); } }; const selectedDate = selectedDate => { const currentDate = selectedDate?.currentDate; const key = String(selectedDate?.state); setScheduleData(prevState => ({...prevState, [key]: currentDate})); }; return ( <ScreenBoiler> <FormScrollContainer> <View style={R.styles.contentView}> <Text variant={'body1'} font={'PoppinsSemiBold'} color={R.color.blackShade4} align={'left'} gutterTop={12} gutterBottom={10} transform={'none'}> Edit Schedule </Text> <View style={R.styles.subContentContainer}> <DropDown gutterTop={12} widthInPercentage={'100%'} arrayData={daysOfWeek} placeholder={'Select Day'} loaderParentCall={data => { setScheduleData({ ...scheduleData, day: data?.value, }); }} schemaLabel={'label'} schemaValue={'value'} value={scheduleData?.day} formError={errorField?.day} /> <TimeDatePicker pickerMode={'date'} state={'startDate'} selectDate={data => { selectedDate(data); }} date={scheduleData?.startDate} placeholder={'Start Date'} formError={errorField?.startDate} /> <TimeDatePicker pickerMode={'date'} state={'endDate'} selectDate={data => { selectedDate(data); }} date={scheduleData?.endDate} placeholder={'End Date'} formError={errorField?.endDate} /> <TextInput secureText={false} onChangeText={text => { setScheduleData({...scheduleData, noOfWeeks: text}); }} placeholder={'No Of Weeks'} titleColor={R.color.black} gutterTop={12} widthInPercentage={'100%'} color={R.color.black} value={String(scheduleData?.noOfWeeks)} formError={errorField?.noOfWeeks} formErrorText={errorField?.noOfWeeks} keyboardType={'numeric'} /> <TimeDatePicker pickerMode={'time'} state={'startTime'} selectDate={data => { selectedDate(data); }} date={scheduleData?.startTime} placeholder={'End Time'} formError={errorField?.startTime} /> <TimeDatePicker pickerMode={'time'} state={'finishTime'} selectDate={data => { selectedDate(data); }} date={scheduleData?.finishTime} placeholder={'Finish Time'} formError={errorField?.finishTime} /> <TextInput secureText={false} onChangeText={text => { setScheduleData({...scheduleData, sessionType: text}); }} placeholder={'Session Type'} titleColor={R.color.black} gutterTop={12} widthInPercentage={'100%'} color={R.color.black} value={scheduleData?.sessionType} formError={errorField?.sessionType} formErrorText={errorField?.sessionType} /> <TextInput secureText={false} onChangeText={text => { setScheduleData({...scheduleData, notes: text}); }} placeholder={'Notes'} titleColor={R.color.black} gutterTop={12} widthInPercentage={'100%'} color={R.color.black} value={scheduleData?.notes} formError={errorField?.notes} formErrorText={errorField?.notes} /> <TextInput secureText={false} onChangeText={text => { setScheduleData({...scheduleData, address: text}); }} placeholder={'Address'} titleColor={R.color.black} gutterTop={12} widthInPercentage={'100%'} color={R.color.black} value={scheduleData?.address} formError={errorField?.address} formErrorText={errorField?.address} /> <TextInput secureText={false} onChangeText={text => { setScheduleData({...scheduleData, staffNotes: text}); }} placeholder={'Staff Notes'} titleColor={R.color.black} gutterTop={12} widthInPercentage={'100%'} color={R.color.black} value={scheduleData?.staffNotes} formError={errorField?.staffNotes} formErrorText={errorField?.staffNotes} gutterBottom={20} /> <Button value={'Submit'} bgColor={R.color.secondaryColor2} width={'100%'} size={'lg'} gutterTop={20} color={R.color.white} borderColor={R.color.secondaryColor2} disabled={isLoading} loader={isLoading} loaderColor={R.color.white} onPress={onSubmit} /> </View> </View> </FormScrollContainer> </ScreenBoiler> ); } export default EditScheduleScreen;
import streamlit as st import torch from torch import nn class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(12, 128) self.fc2 = nn.Linear(128, 1) def forward(self, x): x = torch.relu(self.fc1(x)) # Doing binary classification, torch.sigmoid should be used instead of Softmax return torch.sigmoid(self.fc2(x)) model = Classifier() model.load_state_dict(torch.load('model_titanic.pth', map_location='cpu')) model.eval() st.title('Titanic Dataset') st.sidebar.title('Input Parameters') # Collecting input parameters from the user pclass = st.sidebar.selectbox("Pclass", [1, 2, 3], help="Select the passenger class.", format_func=lambda x: '1st' if x == 1 else '2nd' if x == 2 else '3rd') age = st.sidebar.number_input("Age", min_value=1, value=1, help="Enter the age of the passenger. Minimum value is 1.") sibsp = st.sidebar.number_input("Siblings/Spouses Aboard", min_value=0, value=0, help="Enter the number of siblings/spouses aboard.") parch = st.sidebar.number_input("Parents/Children Aboard", min_value=0, value=0, help="Enter the number of parents/children aboard.") fare = st.sidebar.number_input("Fare", min_value=0.0, value=0.0, help="Enter the fare paid by the passenger.") sex = st.sidebar.selectbox("Sex", ["male", "female"], help="Select the sex of the passenger.") embarked = st.sidebar.selectbox("Embarked", ["C", "Q", "S"], help="Select the embarkation port.") who = st.sidebar.selectbox("Who", ["child", "man", "woman"], help="Select the passenger type (child, man, woman).") # Convert categorical variables to one-hot encoding sex_male = 1 if sex == "male" else 0 embarked_C = 1 if embarked == "C" else 0 embarked_Q = 1 if embarked == "Q" else 0 embarked_S = 1 if embarked == "S" else 0 who_child = 1 if who == "child" else 0 who_man = 1 if who == "man" else 0 who_woman = 1 if who == "woman" else 0 # Create the input feature vector (12 elements) x = [ pclass, age, sibsp, parch, fare, sex_male, embarked_C, embarked_Q, embarked_S, who_child, who_man, who_woman ] # Converting to a tensor x = torch.tensor([x], dtype=torch.float32) labels = ['survive', 'dead'] with torch.no_grad(): y_ = model(x) # Adjusted the prediction logic to use a threshold of 0.5 for binary classification. # This line dynamically computes the prediction based on the input parameters prediction = (y_ >= 0.5).item() st.write('Predicted survival:', labels[prediction])
#include <Arduino.h> #include <HardwareSerial.h> #include <WiFi.h> #include "../include/SerialMessages.h" #include <map> #include <vector> #define MY_SSID "cjweiland" #define MY_WIFI_PASSWORD "areallygoodkey" //pins 16/17 HardwareSerial SerialLink(2); void xxd(const unsigned char* data, unsigned int dataLen) { for (int i = 0; i < dataLen; i++) { Serial.printf("%02hhx ", data[i]); } Serial.println(""); } struct Socket { WiFiClient* m_Socket; unsigned long m_LastSeenTime; unsigned long m_LastKeepaliveTime; unsigned char m_MAC[6]; }; std::map<int, Socket> gSockets; void setup() { Serial.begin(115200); SerialLink.begin(115200); //connect to WiFi WiFi.begin(MY_SSID, MY_WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.println("Waiting for wifi to connect..."); } Serial.println("Connected to WiFi!"); pinMode(2, OUTPUT); digitalWrite(2, HIGH); } void SendCloseSocket(unsigned char mac[6], int sock) { SMsgClose out; out.m_Header.m_UW = UNIQUE_WORD; out.m_Header.m_Length = sizeof(out); memcpy(out.m_Header.m_MAC, mac, 6); out.m_Msg.m_Header.m_Type = NOWMSG_CLOSE; out.m_Msg.m_Socket = sock; WriteToSerial((uint8_t*)&out, sizeof(out), SerialLink); } void CheckSerial() { unsigned char inBuff[1024]; while (SerialLink.available()) { size_t numBytes = ReadFromSerial(inBuff, sizeof(inBuff), SerialLink); if (numBytes <= 0) break; SMsgHeader* header = (SMsgHeader*)inBuff; NowMsgHeader* nowHeader = (NowMsgHeader*)(header + 1); Serial.printf("Got message len = %hu, type = %hhu\n", header->m_Length, nowHeader->m_Type); xxd(inBuff, header->m_Length); //handle this message! switch (nowHeader->m_Type) { case NOWMSG_CONNECT: { NowMsgConnect* msg = (NowMsgConnect*)nowHeader; char ip[16] = {0}; unsigned char* pIP = (unsigned char*)(&msg->m_Address); sprintf(ip, "%hhu.%hhu.%hhu.%hhu", pIP[0], pIP[1], pIP[2], pIP[3]); Serial.printf("Connecting to %s:%hu...\n", ip, msg->m_Port); WiFiClient* sock = new WiFiClient(); SMsgConnectResult out; out.m_Msg.m_Address = msg->m_Address; out.m_Msg.m_Port = msg->m_Port; out.m_Header.m_UW = UNIQUE_WORD; out.m_Header.m_Length = sizeof(out); memcpy(out.m_Header.m_MAC, header->m_MAC, 6); out.m_Msg.m_Header.m_Type = NOWMSG_CONNECT_RESULT; if (!sock->connect(ip, msg->m_Port)) { //TODO: send response that went badly out.m_Msg.m_Socket = -1; WriteToSerial((uint8_t*)&out, sizeof(out), SerialLink); delete sock; return; } //yay! connected! inform the other side Socket s; s.m_Socket = sock; s.m_LastSeenTime = millis(); s.m_LastKeepaliveTime = s.m_LastSeenTime; memcpy(s.m_MAC, header->m_MAC, 6); gSockets[sock->fd()] = s; out.m_Msg.m_Socket = sock->fd(); WriteToSerial((uint8_t*)&out, sizeof(out), SerialLink); } break; case NOWMSG_CLOSE: { SMsgClose* msg = (SMsgClose*)header; std::map<int, Socket>::iterator itr = gSockets.find(msg->m_Msg.m_Socket); if (itr == gSockets.end()) return; //nothing to do //dispose of the socket Socket sock = (*itr).second; sock.m_Socket->stop(); delete sock.m_Socket; gSockets.erase(itr); } break; case NOWMSG_DATA: { SMsgData* msg = (SMsgData*)header; std::map<int, Socket>::iterator itr = gSockets.find(msg->m_Msg.m_Socket); if (itr == gSockets.end()) { //send a Close message to indicate that the connection doesn't exist SendCloseSocket(header->m_MAC, msg->m_Msg.m_Socket); break; } //send an ACK? or maybe not? idk... Socket& sock = (*itr).second; sock.m_LastSeenTime = millis(); unsigned char* outData = (unsigned char*)(msg + 1); unsigned int outLength = header->m_Length - sizeof(SMsgData); if (sock.m_Socket->write(outData, outLength) != outLength) { //close this socket i guess SendCloseSocket(header->m_MAC, msg->m_Msg.m_Socket); //dispose of the socket sock.m_Socket->stop(); delete sock.m_Socket; gSockets.erase(itr); break; } Serial.println("Sent data to wifi successfully!"); } break; case NOWMSG_KEEPALIVE_RESP: { SMsgSocketKeepaliveResponse* msg = (SMsgSocketKeepaliveResponse*)header; Serial.printf("Got keepalive response for %d, in use = %c\n", msg->m_Msg.m_Socket, msg->m_Msg.m_InUse ? 'Y' : 'N'); std::map<int, Socket>::iterator itr = gSockets.find(msg->m_Msg.m_Socket); if (itr == gSockets.end()) break; //nothing to do! Socket& sock = (*itr).second; if (msg->m_Msg.m_InUse) { sock.m_LastSeenTime = sock.m_LastKeepaliveTime = millis(); break; } //not in use! destroy it! sock.m_Socket->stop(); delete sock.m_Socket; gSockets.erase(itr); } break; } //process the next message if it exists } } void CheckSockets() { unsigned char inBuff[250 - sizeof(NowMsgData) + sizeof(SMsgData)] = {0}; SMsgData* outMsg = (SMsgData*)inBuff; outMsg->m_Header.m_UW = UNIQUE_WORD; std::vector<int> socketsToDispose; for (std::map<int, Socket>::iterator itr = gSockets.begin(); itr != gSockets.end(); ++itr) { Socket& sock = (*itr).second; while (sock.m_Socket->available()) { sock.m_LastSeenTime = millis(); size_t numBytes = sock.m_Socket->readBytes(inBuff + sizeof(SMsgData), sizeof(inBuff) - sizeof(SMsgData)); Serial.printf("Received %d bytes from socket %d\n", numBytes, sock.m_Socket->fd()); xxd(inBuff + sizeof(NowMsgData), numBytes); outMsg->m_Header.m_Length = sizeof(SMsgData) + numBytes; memcpy(outMsg->m_Header.m_MAC, sock.m_MAC, 6); outMsg->m_Msg.m_Header.m_Type = NOWMSG_DATA; outMsg->m_Msg.m_Socket = (*itr).first; WriteToSerial(inBuff, sizeof(SMsgData) + numBytes, SerialLink); } unsigned long nowMS = millis(); if (nowMS - sock.m_LastSeenTime > 5000) { Serial.printf("Timing out socket %d!\n", sock.m_Socket->fd()); SendCloseSocket(sock.m_MAC, sock.m_Socket->fd()); socketsToDispose.push_back(sock.m_Socket->fd()); continue; } //send keepalive if necessary if (nowMS - sock.m_LastSeenTime > 2000 && nowMS - sock.m_LastKeepaliveTime > 2000) { //send keepalive Serial.printf("Sending keepalive req for socket %d at %lu\n", sock.m_Socket->fd(), nowMS); SMsgSocketKeepaliveRequest ka; ka.m_Header.m_UW = UNIQUE_WORD; ka.m_Header.m_Length = sizeof(ka); memcpy(ka.m_Header.m_MAC, sock.m_MAC, 6); ka.m_Msg.m_Header.m_Type = NOWMSG_KEEPALIVE_REQ; ka.m_Msg.m_Socket = sock.m_Socket->fd(); WriteToSerial((unsigned char*)&ka, sizeof(ka), SerialLink); sock.m_LastKeepaliveTime = nowMS; //don't send these too frequently } } for (size_t i = 0; i < socketsToDispose.size(); i++) { int sfd = socketsToDispose[i]; Socket& sock = gSockets[sfd]; sock.m_Socket->stop(); delete sock.m_Socket; gSockets.erase(sfd); } } void loop() { CheckSerial(); CheckSockets(); delay(10); }
import { createReducer } from '@reduxjs/toolkit'; import { addRequest, updateRequest, removeRequest, sortRequests, loadFromLocalStorage, } from '../actions'; const initialState = { results: [], }; export const sortRequestsByDate = (sortByDateDispatch) => ({ type: 'localData/sortRequestsByDate', payload: sortByDateDispatch, }); const localData = createReducer(initialState, (builder) => { builder .addCase(loadFromLocalStorage, (state, action) => { const storedData = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); const value = JSON.parse(localStorage.getItem(key)); storedData.push(value); } if (storedData) { return { ...state, results: storedData }; } return state; }) .addCase(addRequest, (state, action) => { const newItem = { ...action.payload }; const updatedResults = [...state.results, newItem]; localStorage.setItem(newItem.id, JSON.stringify(newItem)); return { ...state, results: updatedResults }; }) .addCase(updateRequest, (state, action) => { const updatedItem = action.payload; localStorage.setItem(updatedItem.id, JSON.stringify(updatedItem)); return state; }) .addCase(removeRequest, (state, action) => { const idToRemove = action.payload.id; localStorage.removeItem(idToRemove); return { ...state, results: state.results.filter((item) => item.id !== idToRemove), }; }) .addCase(sortRequests, (state, action) => { const sortByDispatch = action.payload.sortType; const data = [...action.payload.requests]; const itemsWithDate = []; const itemsWithoutDate = []; data.forEach((el, i) => { if (el.date) { itemsWithDate.push(el); } else { itemsWithoutDate.push(el); } }); const sortedItemsWithDate = itemsWithDate.sort((a, b) => { const dateA = sortByDispatch === 'dispatch' ? a.date : a.dateOfCreation; const dateB = sortByDispatch === 'dispatch' ? b.date : b.dateOfCreation; const parsedDateA = Date.parse(dateA.split('/').reverse().join('-')); const parsedDateB = Date.parse(dateB.split('/').reverse().join('-')); return parsedDateB - parsedDateA; }); const sortedResults = [...sortedItemsWithDate, ...itemsWithoutDate]; return { ...state, results: sortedResults }; }) .addDefaultCase((state) => state); }); export default localData;
package com.tqy.scalaMatch object MatchObject { def main(args: Array[String]): Unit = { val user = new User("zhangsan", 23) val result = user match { case User("zhangsan", 23) => "yes" case _ => "no" } println(result) } } // 样例类就是使用case关键字声明的类 // 样例类仍然是类,和普通类相比,只是其自动生成了伴生对象,并且伴生对象中自动提供了一些常用的方法,如apply、unapply、toString、equals、hashCode和copy。 // 样例类是为模式匹配而优化的类,因为其默认提供了unapply方法,因此,样例类可以直接使用模式匹配,而无需自己实现unapply方法。 // 构造器中的每一个参数都成为val,除非它被显式地声明为var(不建议这样做) case class User(str: String,var i: Int) //class User(name:String,age:Int){ // val uname = name; // val uage = age; // // def this(){ // this("",0) // } //} // //object User{ // def unapply(user : User):Option[(String ,Int)] ={ // if(user == null) // None // else // Option(user.uname,user.uage) // } // // //}
#include <iostream> #include<vector> using namespace std; class Solution { public: //归并排序------------------------------------------ static void MergeSort(vector<int>& nums) { if (nums.size() == 1) { return; } //拆分数组 int mid = nums.size() / 2; vector<int> left, right; for (int i = 0; i < mid; i++) { left.push_back(nums[i]); } for (int j = mid; j < nums.size(); ++j) { right.push_back(nums[j]); } //递归调用 MergeSort(left); MergeSort(right); //合并数组 int i = 0, j = 0,k = 0; for (; k < nums.size(); k++) { if (j >= right.size() || ((i < mid) && (left[i] <= right[j]))) //防止出现数组越界 { nums[k] = left[i]; ++i; } else { nums[k] = right[j]; ++j; } } return; } //归并排序------------------------------------------ //打印数组 static void Show(vector<int>& nums) { for (int &i : nums) { cout << i << ' '; } cout << endl; } }; int main() { vector<int> nums = { 1,1,9,16,8,7,5,26,16,17,35,69,42,3,6,12,24,21,36 }; Solution::Show(nums); Solution::MergeSort(nums); Solution::Show(nums); system("pause"); return 0; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/template.css"> <title>Shoe</title> </head> <body> <header class="header"> <nav> <div> <ul class="main-nav"> <li class="main-nav-li li1"><a href="#"><span class="drop" tooltip = "Go to Main Menu">Home</span></a></li> <li class="main-nav-li li1"><a href="men.html"><span class="drop0" tooltip0 = "Go to Men's Section">Men</span></a></li> <li class="main-nav-li li2"><a href="women.html"><span class="drop1" tooltip1 = "Go to Women's Section">Women</span></a></li> <li class="main-nav-li li3"><a href="#form"><span class="drop2" tooltip2 = "Join our Family">Login</span></a></li> <li class="main-nav-li li4"><a href="cart.html"><span class="drop3" tooltip3 = "Go to cart"><ion-icon class="cart" name="cart-outline"></ion-icon></span></a></li> </ul> </nav> </div> <div> <h3 class="company-name">Company name</h3> <ion-icon class="company-logo" name="cube-outline"></ion-icon> </div> </header> <main> <section class="hero-section"> <div> <h1 class="hero-heading">Build your own<br> path with every step.</h1> <div class="sub_hero-heading"<a href="#shopnow"><button class="btn hero-btn">Shop Now</button></a> </div> </section> <div class="categories"> <div class="featured"> <div class="featured-parent"> <img class="img" src="https://images.unsplash.com/photo-1562751361-ac86e0a245d1?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8bGVhdGhlciUyMGphY2tldHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60" alt="1"> </div> <div class="featured-parent"> <img class="img" src="https://images.unsplash.com/photo-1562751361-ac86e0a245d1?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8bGVhdGhlciUyMGphY2tldHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60" alt="2"> </div> <div class="featured-parent"> <img class="img" src="https://images.unsplash.com/photo-1562751361-ac86e0a245d1?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8bGVhdGhlciUyMGphY2tldHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60" alt="3"> </div> </div> </div> <div id="shopnow" class="shopnow"> <div class="sub_shopnow"><h1 class="heading-shop">Shop now</h1></div> <div class="products"> <div class="men"> <img src="images/men.jpg" alt="men"> <a href="men.html"><button class="btn btn-shop-men">Men's</button></a> </div> <div class="women"> <img src="images/women.jpg" alt="women"> <a href="women.html"><button class="btn btn-shop-women">Women's</button></a> </div> </div> </div> <section id="form" class="form1"> <div class"sub_heading-form"> <h1 class="heading-form">We're happy to hear from you</h1> </div> <form method="post" action="#" class="contact-form"> <div class="form"> <div class="name"> <label for="name">Name</label> </div> <div class="input-name"> <input type="text" name="name" id="name" placeholder="Your name" required> </div> </div> <div class="form"> <div class="email"> <label for="email">Email</label> </div> <div class="input-email"> <input type="email" name="email" id="email" placeholder="Your email" required> </div> </div> <div class="form"> <div class="find"> <label for="find-us">How did you find us?</label> </div> <div class="input-find"> <select name="find-us" id="find-us"> <option value="friends" selected>Friends</option> <option value="search">Search engine</option> <option value="ad">Advertisement</option> <option value="other">Other</option> </select> </div> </div> <div class="form"> <div class="newsletter"> <label>Newsletter?</label> </div> <div class="input-newsletter"> <input type="checkbox" name="news" id="news" checked> Yes, please </div> </div> <div class="form"> <div class="message"> <label>Drop us a line</label> </div> <div class="input-message"> <textarea name="message" placeholder="Your message"></textarea> </div> </div> <div> <button class="btn btn-send">Send It!</button> </div> </form> </section> </main> <footer> <div> <div> <ul class="footer-nav"> <li><a href="#">About us</a></li> <li><a href="#">Contact us on:- 123456789</a></li> <li><a href="#">Press</a></li> <li><a href="#">iOS App</a></li> <li><a href="#">Android App</a></li> </ul> </div> <div> <ul class="social-links"> <li><a href="#"><ion-icon name="logo-facebook"></ion-icon></a></li> <li><a href="#"><ion-icon name="logo-twitter"></ion-icon></a></li> <li><a href="#"><ion-icon name="logo-instagram"></ion-icon></a></li> </ul> </div> </div> <div class="copyright"> <p> Copyright &copy; 2021 by Company Name. All rights reserved. </p> </div> </footer> <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script> <script src="index.js"></script> </body> </html>
import React, {useEffect} from 'react'; import {useDispatch,useSelector} from 'react-redux'; import {withRouter} from 'react-router-dom'; import {readPost, unloadPost} from '../../modules/post'; import PostViewer from '../../components/post/PostViewer'; import PostActionButtons from '../../components/post/PostActionButton'; import {setOriginalPost} from '../../modules/write'; import {removePost} from '../../lib/api/posts'; const PostViewerContainer= ({ match,history}) =>{ // 처음 마운트될 때 포스트 읽기 API 요청 const {postId} =match.params; const dispatch =useDispatch(); const {post,error,loading,user} =useSelector(({post,loading,user})=>({ post:post.post, error:post.error, loading:loading['post/READ_POST'], user:user.user, })); useEffect(()=>{ dispatch(readPost(postId)); // 언마운트 될 때 리덕스에서 포스트 데이터 없애기 return()=>{ dispatch(unloadPost()); }; },[dispatch,postId]); const onEdit= ()=>{ dispatch(setOriginalPost(post)); history.push('/write'); }; const onRemove = async ()=>{ try{ await removePost(postId); history.push('/'); // 홈으로 이동 }catch(e){ console.log(e); } }; const ownPost = (user && user._id) === (post && post.user._id); return <PostViewer post={post} loading={loading} error={error} actionButtons={ownPost && <PostActionButtons onEdit={onEdit} onRemove={onRemove}/>} />; }; export default withRouter(PostViewerContainer);
// const multer = require('multer'); // const moment = require('moment'); // // Функция для создания middleware загрузки изображений с параметрами // const createImageUploadMiddleware = (type, required = false) => { // // Где будут загружаться и храниться // const storage = multer.diskStorage({ // destination(req, file, cb) { // const uploadPath = `../stories/images/${type}/`; // Формируем путь для сохранения // cb(null, uploadPath); // Передаем путь в middleware multer // }, // filename(req, file, cb) { // const date = moment().format('DDMMYYYY-HHmmss'); // cb(null, `${date}-${file.originalname}`); // } // }); // // Фильтрация // const fileFilter = (req, file, cb) => { // // Если файл является картинкой // if (file.mimetype === 'image/png' || // file.mimetype === 'image/jpeg' || // file.mimetype === 'image/jpg' || // file.mimetype === 'image/svg+xml') { // cb(null, true); // } else { // cb(null, false); // } // }; // // Размер изображения // const limits = { // fileSize: 1048576 * 100 // 100 Мб // }; // return (req, res, next) => { // const upload = multer({ // storage: storage, // fileFilter: fileFilter, // limits: limits // }).single('image'); // // Если обязательное поле и нет файла, выдаем ошибку // if (required && !req.file) { // return res.status(400).json({ error: 'Файл не загружен' }); // } // // Если файл не обязателен или файл есть, выполняем загрузку // if (!required || req.file) { // upload(req, res, function(err) { // if (err instanceof multer.MulterError) { // // Ошибка Multer при загрузке файла // return res.status(500).json({ error: err.message }); // } else if (err) { // // Неизвестная ошибка // return res.status(500).json({ error: 'Произошла ошибка при загрузке файла' }); // } // // Если все в порядке, переходим к следующему middleware // next(); // }); // } else { // // Если файл не обязателен и его нет, просто переходим к следующему middleware // next(); // } // }; // }; // module.exports = createImageUploadMiddleware; const multer = require('multer'); const moment = require('moment'); // Функция для создания middleware загрузки изображений с параметрами const createImageUploadMiddleware = (type, required = false) => { // Фильтрация const fileFilter = (req, file, cb) => { // Если файл является картинкой if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/svg+xml') { cb(null, true); } else { cb(null, false); } }; // Размер изображения const limits = { fileSize: 1048576 * 100 // 100 Мб }; return (req, res, next) => { const storage = multer.diskStorage({ destination(req, file, cb) { const uploadPath = `../client/public/stories/images/${type}/`; // Формируем путь для сохранения cb(null, uploadPath); // Передаем путь в middleware multer }, filename(req, file, cb) { const date = moment().format('DDMMYYYY-HHmmss'); // cb(null, `${date}-${file.originalname}`); cb(null, `${file.originalname}`); } }); const upload = multer({ storage: storage, fileFilter: fileFilter, limits: limits }).single('file'); // Если обязательное поле и нет файла, выдаем ошибку if (required && !req.file) { return res.status(400).json({ error: 'Файл не загружен' }); } // Если файл не обязателен или файл есть, выполняем загрузку if (!required || req.file) { upload(req, res, function(err) { if (err instanceof multer.MulterError) { // Ошибка Multer при загрузке файла return res.status(500).json({ error: err.message }); } else if (err) { // Неизвестная ошибка return res.status(500).json({ error: 'Произошла ошибка при загрузке файла' }); } // Если все в порядке, переходим к следующему middleware next(); }); } else { // Если файл не обязателен и его нет, просто переходим к следующему middleware next(); } }; }; module.exports = createImageUploadMiddleware;
import os, sys from langchain_core.prompts import ChatPromptTemplate from langchain.prompts.prompt import PromptTemplate from langchain_core.prompts import format_document # basic template for page content DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template(template="{page_content}") def _combine_documents(docs, sep="\n\n"): doc_strings = [format_document(doc, DEFAULT_DOCUMENT_PROMPT) for doc in docs] return sep.join(doc_strings) # final answer/ouptut prompt _template = """You are a friendly chatbot named Bull Buddy. You are here to help USF students with their admissions and onboarding. If you question is general in nature like hi or hello, directly answer the question without using the context provided. If the question is specific to USF or MS BAIS program, use the context provided to answer the user's question. If the question cannot be the answered from the context provided, just say that you don't know and ask the user to e-mail their program advisor for more/any specific information needed. Context: {context} Question: {question} Answer: """ ANSWER_PROMPT = ChatPromptTemplate.from_template(_template) # standard alone _template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in English. Chat History: {chat_history} Follow Up Input: {question} Standalone question:""" CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template) # query augumentation prmompt system = """You are an expert at assisting students regarding University of South Florida's Masters in Business Analytics and Information System program.\ Perform Query Expansion/Augumentation. If there are multiple common ways of phrasing a user question \ or common synonyms for key words in the question, make sure to return multiple versions \ of the query with the different phrasings. If there are acronyms or words you are not familiar with, do not try to rephrase them. Return at least 3 versions of the question.""" QUERY_AUG_PROMPT = ChatPromptTemplate.from_messages( [ ("system", system), ("human", "{question}"), ] ) # HYDE Prompt system = """You are an expert at assisting students regarding University of South Florida's Masters in Business Analytics and Information System program.\ Answer the user question as best you can, addressing the user's concerns. """ HYDE_PROMPT = ChatPromptTemplate.from_messages( [ ("system", system), ("human", "{question}"), ] )
--- sidebar_label: "SSH access" sidebar_position: 5 --- # SSH access SSH is pre-integrated in the official ArmSoM Linux image to facilitate remote access to the terminal. This guide uses ArmSoM-W3 as an example. The operations for other motherboards are similar. ## 1. Necessary preparations * ArmSoM Internet-enabled products * RJ45 network cable * Host PC * Router/Switch Connect ArmSoM-W3 to a router/switch on the same network segment as the host through a network cable. ## 2. Check SSH service status After ArmSoM-W3 starts, you can view the SSH service status through the following command: ``` sudo service ssh status ``` If the SSH service is abnormal or uninstalled, you can restart or reinstall it with the following command: Restart the service: ``` service sshd restart ``` re-install: ``` sudo apt-get update sudo apt-get install ssh ``` ## 3. Query IP address To view through the command line, you can use the serial port/adb/ to directly connect to hdmi. Enter the following command in the terminal to view the IP address. ``` ip a ``` The IP address in the same network segment as the host is the IP address required for SSH connection. For example, in the following output, 192.168.10.59 is the IP address we need: ``` armsom@armsom-w3:~$ ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: enP4p65s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether 8a:e5:4e:f3:ea:5a brd ff:ff:ff:ff:ff:ff permaddr 2a:ab:ea:32:56:cc inet 192.168.10.59/24 brd 192.168.10.255 scope global dynamic noprefixroute enP4p65s0 valid_lft 85861sec preferred_lft 85861sec ``` ### 3.1. Use Angryip to find the IP address of the product When you cannot directly operate the motherboard to obtain the IP address without a screen or remotely, you can use this method to query the IP address. First, the host PC needs to download Angryip, and then ensure that the host PC and the ArmSoM product are in the same LAN. Open Angryip and select the IP range, which ranges from 192.168.10.0 - 192.168.10.255 (select the network segment where the host and motherboard are located). Click Start as shown in the picture. ![Angryip](/img/general-tutorial/Angryip.png) Ctrl + F Search for the armsom keyword and find the IP address. ## 4. Connection Open the host terminal and check whether they are on the same network segment through the ping command: ``` Ping the IP address of the ArmSoM product ``` When connected, the ping results should be normal. *SSH login to ArmSoM-W3 ``` IP address of ssh name@armsom-w3 For example: ssh [email protected] ``` * If local domain is supported, you can use the following command instead of scanning the IP address of ArmSoM-W3. ``` ping armsom-w3.local ssh [email protected] ``` Once properly connected, the terminal switches to the remote terminal of ArmSoM-W3 as shown below: ``` Linux armsom-w3 5.10.160 #1 SMP Wed Nov 8 15:45:13 CST 2023 aarch64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. armsom@armsom-w3:~$ ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: enP4p65s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether 8a:e5:4e:f3:ea:5a brd ff:ff:ff:ff:ff:ff permaddr 2a:ab:ea:32:56:cc inet 192.168.10.59/24 brd 192.168.10.255 scope global dynamic noprefixroute enP4p65s0 valid_lft 85861sec preferred_lft 85861sec ``` You can now operate the terminal.
// // ViewController.swift // PickerViewDemo // // Created by Varun on 06/01/17. // Copyright © 2017 Codekul. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet var myLbl: UILabel! var arrData1 : Array<String> = [] var arrData2 : Array<String> = [] var arrData3 : Array<String> = [] var str1 = "" var str2 = "" var str3 = "" var pickerView : UIPickerView? override func viewDidLoad() { super.viewDidLoad() pickerView = UIPickerView(frame: CGRect(x: 0, y: 176, width: 320, height: 216)) pickerView?.dataSource = self pickerView?.delegate = self self.view.addSubview(pickerView!) arrData1 = Array(arrayLiteral: "Manish", "Shraddha", "Varun","Aniruddha","Nikhil") arrData2 = ["Yamaha","RE","KTM","Benilli","BMW","TVS"] arrData3 = ["Delhi", "Noida","Jammu","Chennai"] str1 = arrData1[0] str2 = arrData2[0] str3 = arrData3[0] myLbl.text = str1 + " " + str2 + " " + str3 } // Datasource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return arrData1.count } else if component == 1 { return arrData2.count } return arrData3.count } // Delegate func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return arrData1[row] } else if component == 1 { return arrData2[row] } return arrData3[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 0 { str1 = arrData1[row] } else if component == 1{ str2 = arrData2[row] } else { str3 = arrData3[row] } myLbl.text = str1 + " " + str2 + " " + str3 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core'; import {MatPaginator} from '@angular/material/paginator'; import {MatTableDataSource} from '@angular/material/table'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Vehiculo } from '../../models/Vehiculo'; import { VehiculoService } from '../../services/vehiculo.service'; import { PlantaService } from 'src/app/pages/plantas/services/planta.service'; import { TiposVehiculosService } from 'src/app/pages/tipos_vehiculos/services/tiposVehiculos.service'; @Component({ selector: 'app-departamento', templateUrl: './vehiculo.component.html', styleUrls: ['./vehiculo.component.css'] }) export class VehiculoComponent implements AfterViewInit, OnInit { vehiculos: Vehiculo[] = [] displayedColumns: string[] = ['vehiculo_placa', 'vehiculo_modelo', 'vehiculo_linea', 'vehiculo_disponible', 'vehiculo_tipovehi_nombre', 'vehiculo_planta_nombre', 'acciones']; dataSource = new MatTableDataSource(this.vehiculos); constructor( private vehiculoService: VehiculoService, private _snackBar: MatSnackBar, private plantaService: PlantaService, private tipoVehiculoService: TiposVehiculosService ){ } ngOnInit(): void { this.cargarLosDatos(); } private async cargarLosDatos() { this.vehiculoService.obtenerTodosLosVehiculos() .subscribe( data => { this.vehiculos = data; this.vehiculos.forEach( elemento => { this.plantaService.obtenerUnaPlanta(elemento.vehiculo_planta_id).subscribe( dato => { elemento.vehiculo_planta_nombre = dato.planta_nombre; } ) }) this.vehiculos.forEach( elemento => { this.tipoVehiculoService.obtenerUnTiposVehiculos(elemento.vehiculo_tiposvehi_id).subscribe( dato => { elemento.vehiculo_tipovehi_nombre = dato.tiposVehi_nombre; } ) }) this.dataSource.data = this.vehiculos; }) } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); } @ViewChild(MatPaginator) paginator!: MatPaginator; ngAfterViewInit() { this.dataSource.paginator = this.paginator; } eliminarRegistro(vehiculo_id: any){ this.vehiculoService.eliminarVehiculo(vehiculo_id).subscribe( respuesta => { if( respuesta !== null || respuesta !== undefined){ this._snackBar.open("Registro Eliminado con éxito!", "" , { duration: 1500, horizontalPosition: "center", verticalPosition: "bottom" }) this.cargarLosDatos(); } } ) } }
import { useState, useEffect } from 'react'; import { H1, H3, P, SubTitle } from './global.styles'; import {ContainerPic, ImageDescription, ImageOTD} from './PicOTD.styles' /** * Default data to the Pic of the Day */ const defaultData ={ title:"error", date: '01-01-1991' , url: '/sky.jpg' , explanation:'error' } /** * * @returns {JSX.Element} PicOTD component with the image and description of the day */ function PicOTD() { const [data, setData] = useState(defaultData); async function getData() { try{ const apiKey = process.env.REACT_APP_NASA_APIKEY const res = await fetch(`https://api.nasa.gov/planetary/apod?api_key=${apiKey}`) const data = await res.json() return{ data } } catch (error) { console.log(error) } } /** * useEffect to get the data from the API */ useEffect(() => { getData().then(({data}) => { setData(data) })}, []) let dataContent = 'error' let content = data.explanation let newContent = content.split(".") if(newContent.length >=4){ dataContent = newContent.slice(0, 4).join(".").concat("...") }else{ dataContent = newContent.join('.') } return ( <ContainerPic id="POTD" > <ImageDescription> <SubTitle>Pic Of The Day</SubTitle> <H1>{data.title}</H1> <P>{dataContent} </P> <H3> - {data.date} - {data.copyright} </H3> </ImageDescription> <ImageOTD> <img src={data.url} alt='Pic Of The Day' /> </ImageOTD> </ContainerPic> ) } export default PicOTD;
<!-- Created By: Jared Longnecker Description: Used to customize a lightning button with default styling. Allows further outside customization to the button through extra attributes. Use instead of lightning:button. --> <aura:component > <!-- Custom Attributes --> <aura:attribute name="hoverColor" type = "String" default = "white" /> <aura:attribute name="hoverTextColor" type = "String" default = "#FBC740" /> <aura:attribute name="textColor" type = "String" default = "white" /> <aura:attribute name="color" type = "String" default = "#FBC740" /> <aura:attribute name="width" type = "String" default = "8em" /> <!-- Lightning Button Attributes --> <aura:attribute name="iconName" type = "String" /> <aura:attribute name="iconPosition" type = "String" default = "left" /> <aura:attribute name="class" type = "String" /> <aura:attribute name="disabled" type = "boolean" default = "false" /> <aura:attribute name="label" type = "String" /> <aura:attribute name="name" type = "String" /> <aura:attribute name="onblur" type = "String" /> <aura:attribute name="onclick" type = "String" /> <aura:attribute name="onfocus" type = "String" /> <aura:attribute name="title" type = "String" /> <!-- Set css variables to attributes for customization --> <aura:html tag="style"> :root { --hoverText: {!v.hoverTextColor}; --hoverColor: {!v.hoverColor}; --textColor: {!v.textColor}; --color: {!v.color}; --width: {!v.width}; } </aura:html> <lightning:button iconName = "{!v.iconName}" iconPosition = "{!v.iconPosition}" class = "{!'button' + v.class}" disabled = "{!v.disabled}" label = "{!v.label}" name = "{!v.name}" onblur = "{!v.onblur}" onclick = "{!v.onclick}" onfocus = "{!v.onfocus}" title = "{!v.title}"/> </aura:component>
import 'package:fluentui_icons/fluentui_icons.dart'; import 'package:flutter/material.dart'; import 'package:jumuiya_app/util/app_colors.dart'; import '../../models/ChartUser.dart'; import '../bottom_nav.dart'; import '../explore_page.dart'; import '../home_page.dart'; import '../members_page.dart'; import '../schedule_page.dart'; import '../user_profile_page.dart'; import 'conversation_list.dart'; class ChatsPage extends StatefulWidget { const ChatsPage({Key? key}) : super(key: key); @override State<ChatsPage> createState() => _ChatsPageState(); } class _ChatsPageState extends State<ChatsPage> { List<ChatUsers> chatUsers = [ ChatUsers(name: "Jane Russel", messageText: "Awesome Setup", imageURL: "https://picsum.photos/250?image=9", time: "Now"), ChatUsers(name: "Glady's Murphy", messageText: "That's Great", imageURL: "https://picsum.photos/250?image=9", time: "Yesterday"), ChatUsers(name: "Jorge Henry", messageText: "Hey where are you?", imageURL: "https://picsum.photos/250?image=9", time: "31 Mar"), ChatUsers(name: "Philip Fox", messageText: "Busy! Call me in 20 mins", imageURL: "https://picsum.photos/250?image=9", time: "28 Mar"), ChatUsers(name: "Debra Hawkins", messageText: "Thankyou, It's awesome", imageURL: "https://picsum.photos/250?image=9", time: "23 Mar"), ChatUsers(name: "Jacob Pena", messageText: "will update you in evening", imageURL: "https://picsum.photos/250?image=9", time: "17 Mar"), ChatUsers(name: "Andrey Jones", messageText: "Can you please share the file?", imageURL: "https://picsum.photos/250?image=9", time: "24 Feb"), ChatUsers(name: "John Wick", messageText: "How are you?", imageURL: "https://picsum.photos/250?image=9", time: "18 Feb"), ]; @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( physics: BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SafeArea( child: Padding( padding: EdgeInsets.only(left: 16,right: 16,top: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), Container( padding: EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), height: 30, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: Color(0xFF687daf), ), child: Row( children: <Widget>[ Icon(Icons.add,color: AppColors.navyBlue ,size: 20,), SizedBox(width: 2,), Text("Add New",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), ], ), ), ], ), ), ), Padding( padding: EdgeInsets.only(top: 16,left: 16,right: 16), child: TextField( decoration: InputDecoration( hintText: "Search...", hintStyle: TextStyle(color: Colors.grey.shade600), prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), filled: true, fillColor: Colors.grey.shade100, contentPadding: EdgeInsets.all(8), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide( color: Colors.grey.shade100 ) ), ), ), ), Column( children: [ ListView.builder( itemCount: chatUsers.length, shrinkWrap: true, padding: EdgeInsets.only(top: 16), physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index){ return ConversationList( name: chatUsers[index].name, messageText: chatUsers[index].messageText, imageUrl: chatUsers[index].imageURL, time: chatUsers[index].time, isMessageRead: (index == 0 || index == 3)?true:false, ); }, ) ], ) ], ), ), ); } }
import { Form, Formik } from "formik"; import { useTasks } from "../context/TaskContext"; import { useParams, useNavigate } from "react-router-dom"; import { useEffect, useState } from "react"; export const TaskForm = () => { const { createTask, getTask, updateTask } = useTasks(); const [task, setTask] = useState({ title: "", description: "" }) const params = useParams(); const navigate = useNavigate(); useEffect(() => { const loadTask = async() => { if(params.id){ const task = await getTask(params.id); setTask({ title: task.description, description: task.description }) } } loadTask(); }, []) return ( <div> <Formik initialValues={task} enableReinitialize={true} onSubmit= { async ( values, actions ) => { console.log(values); if (params.id) { await updateTask(params.id, values); }else{ createTask(values); } navigate("/") actions.resetForm(); }} >{({ handleChange, handleSubmit, values, isSubmitting }) => ( <Form onSubmit={ handleSubmit} className="bg-slate-300 max-w-sm rounded-md p-4 mx-auto mt-10"> <h1 className="text-xl font-bold uppercase text-center">{ params.id ? "Edit Task" : "New Task" }</h1> <label className="block">Title</label> <input type="text" name="title" placeholder="Write a Title" className="px-2 py-1 rounded-sm w-full" onChange={handleChange} value = {values.title} /> <label className="block">Description</label> <textarea name="description" rows="3" onChange={handleChange} placeholder="Write a description" className="px-2 py-1 rounded-sm w-full" value = {values.description} ></textarea> <button type="submit" disabled={isSubmitting} className="block bg-indigo-500 px-2 py-1 text-white w-full rounded-md"> {isSubmitting ? "Saving..." : "Save"} </button> </Form> )} </Formik> </div> ) }