text
stringlengths 184
4.48M
|
|---|
/*
* The MIT License
*
* Copyright 2022 Mastfrog Technologies.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.mastfrog.giulius.thread;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.mastfrog.function.state.Obj;
import com.mastfrog.giulius.Dependencies;
import com.mastfrog.giulius.thread.wrap.ExecutionWrapper;
import com.mastfrog.giulius.thread.wrap.GranularExecutionWrapper;
import com.mastfrog.settings.Settings;
import com.mastfrog.settings.SettingsBuilder;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;
/**
*
* @author Tim Boudreau
*/
public class WrappingExecutorTest {
private static final ThreadLocal<String> LOC = new ThreadLocal<>();
private static final Key<ExecutorService> stuffKey = Key.get(ExecutorService.class, Names.named("stuff"));
private Dependencies deps;
private ExecutorService stuff;
private TestExeWrapper exeWrap;
@Test
public void testPropagation() throws Throwable {
LOC.set("hey");
Obj<String> val = Obj.createAtomic();
Obj<String> val2 = Obj.createAtomic();
CountDownLatch latch = new CountDownLatch(2);
stuff.submit(() -> {
val.set(LOC.get());
LOC.set("whee");
stuff.submit(() -> {
val2.set(LOC.get());
latch.countDown();
});
latch.countDown();
});
latch.await(10, TimeUnit.SECONDS);
assertEquals("hey", val.get());
assertEquals("whee", val2.get());
assertEquals("hey", LOC.get());
exeWrap.assertSubmits(2)
.assertBeforeRuns(2)
.assertAfterRuns(2)
.rethrow();
}
@Before
public void before() throws IOException {
exeWrap = new TestExeWrapper();
ThreadModule tm = new ThreadModule();
tm.builder("stuff")
.withExplicitThreadCount(1)
.withDefaultThreadCount(1)
.withThreadPoolType(ThreadPoolType.STANDARD)
.withUncaughtExceptionHandler((Thread t, Throwable e) -> {
e.printStackTrace();
})
.propagatingThreadLocal(LOC)
.wrappingSubmissionsWith(exeWrap)
.daemon()
.bind();
deps = new Dependencies(Settings.builder().build(), tm);
stuff = deps.getInstance(stuffKey);
}
@After
public void after() {
if (deps != null) {
deps.shutdown();
}
}
static class TestExeWrapper implements GranularExecutionWrapper<String, String> {
private final AtomicInteger submits = new AtomicInteger();
private final AtomicInteger beforeRuns = new AtomicInteger();
private final AtomicInteger afterRuns = new AtomicInteger();
private final CopyOnWriteArrayList<Throwable> throwns = new CopyOnWriteArrayList<>();
public TestExeWrapper assertSubmits(int count) {
assertEquals("Wrong number of calls to onSubmit", count, submits.get());
return this;
}
public TestExeWrapper assertBeforeRuns(int count) {
assertEquals("Wrong number of calls to onBeforeRun", count, beforeRuns.get());
return this;
}
public TestExeWrapper assertAfterRuns(int count) {
assertEquals("Wrong number of calls to onAfterRun", count, afterRuns.get());
return this;
}
public TestExeWrapper rethrow() throws Exception {
if (!throwns.isEmpty()) {
Exception ex = new Exception("Exceptions were thrown");
throwns.forEach(ex::addSuppressed);
throwns.clear();
throw ex;
}
return this;
}
@Override
public String onSubmit() {
submits.incrementAndGet();
return "submitting";
}
@Override
public String onBeforeRun(String t) {
beforeRuns.incrementAndGet();
assertEquals("submitting", t);
return "beforeRun";
}
@Override
public boolean onAfterRun(String fromSubmit, String fromRun, Throwable thrown) {
afterRuns.incrementAndGet();
if (thrown != null) {
throwns.add(thrown);
}
assertEquals("submitting", fromSubmit);
assertEquals("beforeRun", fromRun);
assertNull(thrown);
return true;
}
}
}
|
import 'package:flutter/material.dart';
import 'package:ioe/constants.dart';
import 'package:ioe/screens/components/insidebuttons.dart';
import 'package:ioe/screens/components/pdfviewfunction.dart';
import 'package:ioe/screens/components/syllabuscontent.dart';
class DesignofRCCStructure extends StatelessWidget {
final int initialTabIndex;
DesignofRCCStructure({this.initialTabIndex = 0});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
initialIndex: initialTabIndex,
child: Scaffold(
appBar: AppBar(
title: Text(
'Design of RCC Structure',
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
bottom: TabBar(
tabs: [
Tab(
child: Text(
'Notes',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
),
Tab(
child: Text(
'Syllabus',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
)),
Tab(
child: Text(
'Old Questions',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
)),
],
indicatorColor: kblue,
labelColor: Colors.black,
),
),
body: TabBarView(
//physics: NeverScrollableScrollPhysics(),
children: [
_buildNotesTab(context),
_buildSyllabusTab(),
_buildOldQuestionsTab(context),
],
),
),
);
}
Widget _buildNotesTab(BuildContext context) {
return ListView(
padding: EdgeInsets.symmetric(horizontal: 16.0),
children: [
SizedBox(height: 20),
InsideButtons(
text: 'Beam And Frame',
icon: Icons.arrow_forward,
onTap: () {
openPDF(context,
'https://notesioe.com/wp-content/uploads/2023/11/matrix.pdf');
},
),
SizedBox(height: 10),
InsideButtons(
text: 'Kinetics And Kinematics',
icon: Icons.arrow_forward,
onTap: () async {
openPDF(context,
'https://notesioe.com/wp-content/uploads/2023/11/matrix.pdf');
},
),
SizedBox(height: 10),
InsideButtons(
text: 'Truss',
icon: Icons.arrow_forward,
onTap: () async {
openPDF(context,
'https://notesioe.com/wp-content/uploads/2023/11/Polarization.pdf');
},
),
SizedBox(height: 10),
InsideButtons(
text: 'Centroid',
icon: Icons.arrow_forward,
onTap: () async {
openPDF(context,
'https://notesioe.com/wp-content/uploads/2023/11/एक-चिहान-उपन्यास-.pdf');
},
),
SizedBox(height: 10),
InsideButtons(
text: 'Friction',
icon: Icons.arrow_forward,
onTap: () async {
openPDF(context,
'https://notesioe.com/wp-content/uploads/2023/11/matrix.pdf');
},
),
// Add more InsideButtons as needed
],
);
}
Widget _buildSyllabusTab() {
return SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//SizedBox(height: 10),
SectionHeader(text: 'Marks Distribution'),
SizedBox(height: 10),
Container(
padding: EdgeInsets.all(8.0),
child: Table(
border: TableBorder.all(),
children: [
TableRow(
children: [
TableCell(
child: Center(child: Text('Chapters')),
),
TableCell(
child: Center(child: Text('Hours')),
),
TableCell(
child: Center(child: Text('Marks')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('1')),
),
TableCell(
child: Center(child: Text('3')),
),
TableCell(
child: Center(child: Text('4')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('2')),
),
TableCell(
child: Center(child: Text('4')),
),
TableCell(
child: Center(child: Text('4')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('3')),
),
TableCell(
child: Center(child: Text('5')),
),
TableCell(
child: Center(child: Text('6')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('4')),
),
TableCell(
child: Center(child: Text('6')),
),
TableCell(
child: Center(child: Text('12')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('5, 6, 7')),
),
TableCell(
child: Center(child: Text('10')),
),
TableCell(
child: Center(child: Text('12')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('8')),
),
TableCell(
child: Center(child: Text('6')),
),
TableCell(
child: Center(child: Text('6')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('9')),
),
TableCell(
child: Center(child: Text('6')),
),
TableCell(
child: Center(child: Text('12')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('10')),
),
TableCell(
child: Center(child: Text('8')),
),
TableCell(
child: Center(child: Text('12')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('11')),
),
TableCell(
child: Center(child: Text('6')),
),
TableCell(
child: Center(child: Text('6')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('12')),
),
TableCell(
child: Center(child: Text('6')),
),
TableCell(
child: Center(child: Text('6')),
),
],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('Total')),
),
TableCell(
child: Center(child: Text('60')),
),
TableCell(
child: Center(child: Text('80')),
),
],
),
],
),
),
SizedBox(height: 10),
Text('There may be minor deviation in marks distribution.'),
//SizedBox(height: 20),
SectionHeader(
text: 'Concrete Structures and Design Methods [3 hours]'),
SubSection(text: 'Introduction to Reinforced Concrete Structures'),
SubSection(text: 'Design methods of Reinforced Concrete Structures'),
SubSection(text: 'Characteristic strengths and loads'),
SubSection(text: 'Design process and basis for design'),
SectionHeader(text: 'Working Stress Method of Design [4 hours]'),
SubSection(text: 'Basic assumption in working stress design'),
SubSection(
text:
'Working load and permissible stresses in concrete and steel'),
SubSection(text: 'Behavior of beam under loading'),
SubSection(
text:
'Types of reinforced concrete beam and different RC sections'),
SubSection(text: 'Design of singly reinforced rectangular beam'),
SectionHeader(text: 'Limit State Method of design [5 hours]'),
SubSection(
text:
'Safety and serviceability requirements and different limit states of structure'),
SubSection(text: 'Design strength of materials and design loads'),
SubSection(
text: 'Idealized stress-strain diagram of concrete and steel'),
SubSection(
text:
'Limit state of collapse in flexure, shear, torsion and compression'),
SubSection(
text:
'Limit state of serviceability in deflection and in cracking'),
SectionHeader(text: 'Design of beams: Behavior in Flexure [6 hours]'),
SubSection(text: 'Flexural behavior of reinforced concrete'),
SubSection(text: 'Design of Rectangular beams'),
SubSection(text: 'Design of flanged beam sections'),
SectionHeader(text: 'Design for Shear and Torsion [4 hours]'),
SubSection(text: 'Shear stress in beams'),
SubSection(text: 'Behavior of concrete under shear'),
SubSection(text: 'Behavior and design strength in Torsion'),
SectionHeader(
text: 'Design for bond and development length [2 hours]'),
SubSection(text: 'Development length'),
SubSection(text: 'Anchorage bond'),
SubSection(text: 'Flexural bond'),
SectionHeader(
text: 'Reinforcement detailing: Codal Provisions [4 hours]'),
SubSection(text: 'Requirements for good detailing'),
SubSection(text: 'Nominal cover'),
SubSection(text: 'Curtailment of Flexural Reinforcement'),
SubSection(text: 'Shear reinforcement'),
SubSection(text: 'Splicing of reinforcement'),
SubSection(text: 'Anchorage'),
SubSection(text: 'Bar bending schedule'),
SectionHeader(
text:
'Limit States of Serviceability: Deflection and Cracking [6 hours]'),
SubSection(
text:
'Elastic theory: Cracked, uncracked and partially cracked sections'),
SubSection(text: 'Short-term and long-term deflections'),
SubSection(text: 'Control of deflection in design'),
SubSection(text: 'Control of cracking in design'),
SectionHeader(text: 'Design of slabs and staircase [6 hours]'),
SubSection(text: 'Design of one-way and two-way slabs'),
SubSection(text: 'Detailing of one-way and two-way slabs'),
SubSection(
text: 'Design and detailing of longitudinally loaded stairs'),
SectionHeader(
text: 'Design of compression members: Columns [8 hours]'),
SubSection(text: 'Effective length of columns'),
SubSection(text: 'Design of short columns'),
SubSection(text: 'Design of long columns'),
SubSection(text: 'Reinforcement detailing'),
SectionHeader(text: 'Design of Footings [6 hours]'),
SubSection(text: 'Design of spread footing'),
SubSection(text: 'Design of isolated footings'),
SubSection(text: 'Design of combined footings'),
SubSection(text: 'Design of mat foundation'),
SectionHeader(
text:
'Introduction to Earthquake Resistant Design and Provisions for Ductile Detailing [6 hours]'),
SubSection(text: 'Damage to RCC structures in earthquake'),
SubSection(
text:
'Philosophy of design of structures in earthquake prone region'),
SubSection(text: 'Design for strength and ductility'),
SubSection(text: 'Provision of ductility in building codes'),
SubSection(text: 'Ductility requirement for beam, column and joints'),
SectionHeader(text: 'Tutorials'),
SubSection(
text:
'Design and detailing of rectangular and flanged beams [4 hours]'),
SubSection(text: 'Flexure [4 hours]'),
SubSection(text: 'Shear/ Tortion [4 hours]'),
SubSection(text: 'Bending [2 hours]'),
SubSection(text: 'Serviceability [4 hours]'),
SubSection(
text: 'Design and detailing of slabs and staircase [4 hours]'),
SubSection(text: 'Design and detailing of columns [4 hours]'),
SubSection(text: 'Design and detailing of footings [4 hours]'),
SubSection(text: 'Ductile Detailing [4 hours]'),
SectionHeader(text: 'Project work'),
SubSection(
text:
'Individual project to and design elements of a low rise building'),
SectionHeader(text: 'Practical'),
SubSection(text: 'Test a beam in pure bending failure'),
SubSection(text: 'Test a beam in pure shear failure'),
SubSection(text: 'Test a beam in combined bending shear failure'),
SubSection(
text:
'Practical work on making skeleton of beam-column connection'),
SubSection(text: 'Practical work on making skeleton of beam-slab'),
SectionHeader(text: 'References:'),
SubSection(
text:
'Jain, A.K. 2002. Reinforced Concrete Limit State Design, Nem Chand and Bros, Roorkee, India (Reprint 2009)'),
SubSection(
text:
'Pillai, S.U., Menon, D. 2011. Reinforced Concrete Design, Tata McGraw Hill Education Private Limited, New Delhi'),
SubSection(
text:
'Kong, F.K., Evans, R.H. 1987. Reinforced and Pre-stressed Concrete, ELBS, London'),
SubSection(
text:
'Agrawal, P., Shrikhande, M. 2006. Earthquake Resistant Design of Structures, PHI Learning Private Limited, New Delhi (Reprint 2008)'),
SubSection(
text:
'Dayaratnam, P. Design of Reinforced Concrete Structures, Oxford and IBH Publishing Company')
// Syllabus content here
],
),
);
}
Widget _buildOldQuestionsTab(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(height: 20),
InsideButtons(
text: 'Old Questions',
icon: Icons.question_answer_outlined,
onTap: () {
openPDF(context,
'https://notesioe.com/wp-content/uploads/2024/04/AppliedMechanicsOldQues.pdf');
},
),
],
),
),
);
}
}
|
const { response } = require("express");
var express = require("express");
const variables = require("../config/variables");
const productHelpers = require("../helpers/product-helpers");
const staff_helper = require("../helpers/staff_helper");
const userHelpers = require("../helpers/user-helpers");
var router = express.Router();
const verifyLogin = (req, res, next) => {
if (req.session.staff_status) {
next();
} else {
res.redirect(`/staff/login`);
}
};
router.get("/", verifyLogin,function (req, res, next) {
res.redirect('/staff/viewapplications')
});
router.get("/login", function (req, res, next) {
res.render(`staff/login`, {
adminLogErr: req.session.adminLogErr,
MESSAGE:req.session.MESSAGE,
static: true,
});
req.session.MESSAGE = null;
res.render('staff/login',{staff_login:true,MESSAGE:req.session.MESSAGE})
});
router.post("/login", function (req, res, next) {
staff_helper.doLogin(req.body).then(async (response) => {
if (response.status) {
let email = req.body.email;
req.session.staff = response.data;
req.session.staff_status = true;
res.redirect(`/staff`);
} else {
req.session.MESSAGE = {
message:response.message,
status:false,
}
res.redirect(`/staff/login`);
}
});
});
router.get("/logout", (req, res) => {
req.session.staff = null;
req.session.staff_status = null;
res.redirect(`/staff/`);
});
router.get('/viewapplications', verifyLogin, async(req, res) => {
let results = await staff_helper.getApplications()
let auth = req.session.staff;
res.render(`staff/view-applications`, {
staff:true,
results,
auth,
});
})
router.get("/view-application/:id", verifyLogin, async (req, res) => {
let _id = req.session.RedirectPurposeStoreID__DeleteSubCategory = req.params.id;
let result = await staff_helper.getApplication(req.params.id)
console.log(result);
let auth = req.session.staff;
res.render(`staff/view-application`,
{
staff:true,
auth,
result,
_id
});
});
router.get("/viewapplications/:status", verifyLogin, async (req, res) => {
let _id = req.session.RedirectPurposeStoreID__DeleteSubCategory = req.params.status;
staff_helper.getApplicationStatusFilter(req.params.status).then((results)=>{
console.log(results);
let auth = req.session.staff;
res.render(`staff/view-application-pending`,
{
staff:true,
auth,
results,
_id
});
})
// let name = req.session.Name_Show_Subcategory_View = req.params.name
});
router.get("/viewapplications-approvel/:status/:id", verifyLogin, (req, res) => {
// let _id = req.session.SubCat = req.params.id;
// req.session.SubCatName = req.params.name;
// let name = req.params.name;
let auth = req.session.staff;
staff_helper.updateStatus(req.params.status,req.params.id)
// let FormStatus = req.session.Data_Added_SubCat_Status;
res.redirect(`/staff/viewapplications/${req.session.RedirectPurposeStoreID__DeleteSubCategory}`);
req.session.Data_Added_SubCat_Status = null;
});
router.get("/edit-profile", verifyLogin, (req, res) => {
let auth = req.session.staff;
let Edit_Response = req.session.MESSAGE
staff_helper.getTecherData(req.session.staff._id).then((data) => {
res.render(`staff/edit-profile`, { staff:true, data, auth, MESSAGE:req.session.MESSAGE });
req.session.MESSAGE = null
});
});
//----------POST-EDIT-PROFILE----------//
router.post("/edit-profile", verifyLogin, async (req, res) => {
console.log(req.body);
let id = req.session.staff._id
staff_helper.editProfile(req.body,id).then((response)=>{
req.session.MESSAGE ={
message:"Successfully updated",
status:true,
}
res.redirect('/staff/edit-profile')
})
});
router.get("/all-users", verifyLogin, (req, res) => {
productHelpers.getUserDetails().then((userData) => {
userData = userData.users
let auth = req.session.staff;
res.render(`staff/all-users`, {
staff:true,
userData,
auth,
});
});
});
// -------------------------------
router.get("/view-services", verifyLogin, (req, res) => {
userHelpers.getServices().then((response) => {
res.render(`staff/view-services`, {
staff:true,
Admin : req.session.admin,
response,
});
})
});
router.post("/delete-services/:type", verifyLogin, (req, res) => {
productHelpers.deleteService(req.params.type).then((response) => {
if (response.status) {
res.json({ status: true })
} else {
res.json({ status: false })
}
});
});
router.get("/create-services", verifyLogin, (req, res) => {
res.render('staff/create-services',
{
staff:true,
Admin: req.session.admin,
MESSAGE: req.session.MESSAGE
})
req.session.MESSAGE = null
})
router.post("/create-services", verifyLogin, (req, res) => {
productHelpers.createServices(req.body).then(() => {
req.session.MESSAGE = {
message: 'Successfully inserted',
status: true
}
res.redirect('/staff/create-services')
}).catch((err) => {
req.session.MESSAGE = {
message: err.message,
status: false
}
res.redirect('/staff/create-services')
})
})
module.exports = router;
|
"use client";
import Link from "next/link";
import { BiMessageDetail, BiUser } from "react-icons/bi";
import { HiOutlineCog6Tooth, HiOutlineUserGroup } from "react-icons/hi2";
import { useState } from "react";
import { useCurrentUser } from "@/hooks/use-current-user";
import { User } from "next-auth";
import { SettingModal } from "./setting-modal";
import { GroupChatModal } from "@/app/conversations/components/group-chat-modal";
import { usePathname } from "next/navigation";
interface ActionsContentProps {
items: User[];
}
export const MobileFooter: React.FC<ActionsContentProps> = ({ items }) => {
const currentUser = useCurrentUser();
const pathname = usePathname();
const isConversationsOrUsersRoute = /\/(conversations|users)$/i.test(
pathname || ""
);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isSettingModal, setIsSettingModal] = useState(false);
const buttonClass =
"flex flex-col items-center gap-y-2 w-full justify-center p-4 cursor-pointer truncate hover:opacity-50";
const buttonTextClass =
"text-sm font-medium text-foreground dark:text-muted-foreground hidden ms:block";
const buttonIconClass = "dark:text-white";
if (!isConversationsOrUsersRoute) return null;
return (
<div className="fixed bottom-0 z-40 flex w-screen items-center justify-between border-t-[.0625rem] bg-background lg:hidden">
<Link href="/users" className={buttonClass}>
<BiUser size={24} className={buttonIconClass} />
<span className={buttonTextClass}>Users</span>
</Link>
<Link href="/conversations" className={buttonClass}>
<BiMessageDetail size={24} className={buttonIconClass} />
<span className={buttonTextClass}>Messages</span>
</Link>
<SettingModal
isOpen={isSettingModal}
onClose={() => setIsSettingModal(!isSettingModal)}
currentUser={currentUser!}
>
<div className={buttonClass}>
<HiOutlineCog6Tooth size={24} className={buttonIconClass} />
<span className={buttonTextClass}>Settings</span>
</div>
</SettingModal>
<GroupChatModal
data={items}
isOpen={isModalOpen}
onToggleModal={() => setIsModalOpen(!isModalOpen)}
>
<div className={buttonClass}>
<HiOutlineUserGroup size={24} className={buttonIconClass} />
<span className={buttonTextClass}>Group</span>
</div>
</GroupChatModal>
</div>
);
};
|
# Zipcode-Real-Estate-Investment
## Introduction
Choosing where to invest money is crucial for long term success and financial stability, most trust funds and financial planners have different algorithms and ways to predict return on investment and where clients should invest money.
This project will use time series forecasting models created with Python to determine the three zip codes that are the best investment opportunity for a Real Estate Investment Trust.
I completed an initial data analysis on four Arkansas metro areas: Hot Springs, Little Rock, Fayetteville, and Searcy from 1997 to the present before using various models to assess the best zip codes for real estate investment.
## Analysis
First I read in the dataframe with zillow data on average home value by zipcode over the last 20 years.

I removed n’s from the data as there were some missing values for some zip codes. I then created a tim series line graph for each of AR largest metro areas, Hot Springs, Little Rock, Fayetteville and Searcy. I aggregated the graphs onto one visualization shown below.

I then dropped the columns from the dataframe that would not be included in the ARIMA model. RegionID, City, State, CountyName, RegionType and StateName were removed.
I created a 5 year and 3 year ROI for each zipcode.

I then changed the data from wide format to long using melt and changed sipcode to a string and the date column to datetime.


I plotted the average home value by month for all zipcodes and the top ten mean value zipcodes.
To limit the runtime for the processing of the model I took only the zip codes in the top 1% of ROI to use in the model and dropped the metro and sizerank columns so that I could feed the zip codes and values into a list to loop into a dictionary to use as a dataframe with each zipcode as a column and dates as rows.
I chose one zip code to use as a model to find the acf and pacf values.

A train dataset was created using 80% of the dataset and the remaining 20% was used to create a test dataset to test the accuracy of the models. I split the data into a train and test set with 80% of the instances used in the training set. And ran the arima model with a p, q and d of 1 to test the efficacy.

As you can see the model did not accurately predict the test set so I used the auto arima package to find the optimal order for the model. The resulting model was SARIMAX(0,2,0) this was then used in a loop for all zip codes to predict home values through 2024 with an upper and lower confidence interval.
Below are the three most valuable zipcodes with the highest ROI based on the model.



## Conclusion
To down sample I took the zip codes with the highest calculated 5 year ROI. After using the auto arima to calculate the optimal order for the model the zip codes that would provide the best investment were 90020, 90212, 90211. These all provided a predicted ROI of over 1.7 and based on the confidence intervals have very low risk involved for the investor. There were other zip codes that were cheaper to invest in if the trust is low on funds but given the exponential increase in housing prices in California in recent years this investment strategy makes sense if the trust has the necessary capital to invest.
|
package tracker.testutil;
import static tracker.logic.commands.CommandTestUtil.VALID_ADDRESS_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_ADDRESS_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_BUSINESS_SIZE_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_BUSINESS_SIZE_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_COMPANY_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_COMPANY_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_EMAIL_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_EMAIL_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_NAME_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_NAME_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_PHONE_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_PHONE_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_PRIORITY_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_PRIORITY_BOB;
import static tracker.logic.commands.CommandTestUtil.VALID_TAG_FRIEND;
import static tracker.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND;
import static tracker.logic.commands.CommandTestUtil.VALID_TRANSACTION_COUNT_AMY;
import static tracker.logic.commands.CommandTestUtil.VALID_TRANSACTION_COUNT_BOB;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import tracker.model.BookTracker;
import tracker.model.book.Book;
/**
* A utility class containing a list of {@code Person} objects to be used in tests.
*/
public class TypicalPersons {
public static final Book ALICE = new PersonBuilder().withName("Alice Pauline")
.withAddress("123, Jurong West Ave 6, #08-111").withEmail("alice@example.com")
.withPhone("94351253").withBusinessSize("2").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0")
.withTags("friends").build();
public static final Book BENSON = new PersonBuilder().withName("Benson Meier")
.withAddress("311, Clementi Ave 2, #02-25")
.withEmail("johnd@example.com").withPhone("98765432")
.withBusinessSize("23").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0")
.withTags("owesMoney", "friends").build();
public static final Book CARL = new PersonBuilder().withName("Carl Kurz").withPhone("95352563")
.withEmail("heinz@example.com").withAddress("wall street")
.withBusinessSize("234").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0").build();
public static final Book DANIEL = new PersonBuilder().withName("Daniel Meier").withPhone("87652533")
.withEmail("cornelia@example.com").withAddress("10th street")
.withBusinessSize("2345").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0").withTags("friends").build();
public static final Book ELLE = new PersonBuilder().withName("Elle Meyer").withPhone("9482224")
.withEmail("werner@example.com").withAddress("michegan ave")
.withBusinessSize("23456").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0").build();
public static final Book FIONA = new PersonBuilder().withName("Fiona Kunz").withPhone("9482427")
.withEmail("lydia@example.com").withAddress("little tokyo")
.withBusinessSize("234567").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0").build();
public static final Book GEORGE = new PersonBuilder().withName("George Best").withPhone("9482442")
.withEmail("anna@example.com").withAddress("4th street")
.withBusinessSize("2345678").withCompany("software engineering is not cs")
.withPriority("HIGH").withTransactionCount("0").build();
// Manually added
public static final Book HOON = new PersonBuilder().withName("Hoon Meier").withPhone("8482424")
.withEmail("stefan@example.com").withAddress("little india")
.withBusinessSize("10").withCompany("menialtask8")
.withPriority("HIGH").withTransactionCount("0").build();
public static final Book IDA = new PersonBuilder().withName("Ida Mueller").withPhone("8482131")
.withEmail("hans@example.com").withAddress("chicago ave")
.withBusinessSize("10").withCompany("menialtask9")
.withPriority("HIGH").withTransactionCount("0").build();
// Manually added - Person's details found in {@code CommandTestUtil}
public static final Book AMY = new PersonBuilder().withName(VALID_NAME_AMY).withPhone(VALID_PHONE_AMY)
.withEmail(VALID_EMAIL_AMY).withAddress(VALID_ADDRESS_AMY)
.withBusinessSize(VALID_BUSINESS_SIZE_AMY).withCompany(VALID_COMPANY_AMY).withPriority(VALID_PRIORITY_AMY)
.withTransactionCount(VALID_TRANSACTION_COUNT_AMY)
.withTags(VALID_TAG_FRIEND).build();
public static final Book BOB = new PersonBuilder().withName(VALID_NAME_BOB).withPhone(VALID_PHONE_BOB)
.withEmail(VALID_EMAIL_BOB).withAddress(VALID_ADDRESS_BOB)
.withBusinessSize(VALID_BUSINESS_SIZE_BOB).withCompany(VALID_COMPANY_BOB)
.withPriority(VALID_PRIORITY_BOB).withTransactionCount(VALID_TRANSACTION_COUNT_BOB)
.withTags(VALID_TAG_HUSBAND, VALID_TAG_FRIEND)
.build();
public static final String KEYWORD_MATCHING_MEIER = "Meier"; // A keyword that matches MEIER
private TypicalPersons() {} // prevents instantiation
/**
* Returns an {@code AddressBook} with all the typical persons.
*/
public static BookTracker getTypicalAddressBook() {
BookTracker ab = new BookTracker();
for (Book person : getTypicalPersons()) {
ab.addBook(person);
}
return ab;
}
public static List<Book> getTypicalPersons() {
return new ArrayList<>(Arrays.asList(ALICE, BENSON, CARL, DANIEL, ELLE, FIONA, GEORGE));
}
}
|
package repository
import (
"context"
"fmt"
"github.com/pikachu0310/hackathon-23winter/internal/migration"
"golang.org/x/crypto/bcrypt"
"github.com/google/uuid"
)
type (
// users table
User struct {
ID uuid.UUID `db:"id"`
Name string `db:"name"`
CreatedAt string `db:"created_at"`
}
CreateUserParams struct {
Name string
Password string
}
CreateUserByIDParams struct {
ID uuid.UUID
}
)
func (r *Repository) GetUsers(ctx context.Context) ([]User, error) {
var users []User
if err := r.db.SelectContext(ctx, &users, "SELECT id, name, created_at FROM users"); err != nil {
return nil, fmt.Errorf("select users: %w", err)
}
return users, nil
}
func (r *Repository) CreateUser(ctx context.Context, params CreateUserParams) (uuid.UUID, error) {
userID := uuid.New()
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(params.Password), bcrypt.DefaultCost)
if err != nil {
return uuid.Nil, fmt.Errorf("hash password: %w", err)
}
if _, err := r.db.ExecContext(ctx, "INSERT INTO users (id, name, password) VALUES (?, ?, ?)", userID, params.Name, hashedPassword); err != nil {
return uuid.Nil, fmt.Errorf("insert user: %w", err)
}
return userID, nil
}
func (r *Repository) GetHashedPassword(ctx context.Context, userName string) ([]byte, error) {
var storedPassword string
err := r.db.QueryRowContext(ctx, "SELECT password FROM users WHERE name = ?", userName).Scan(&storedPassword)
if err != nil {
return nil, fmt.Errorf("select password: %w", err)
}
return []byte(storedPassword), nil
}
func (r *Repository) GetUserID(ctx context.Context, userName string) (uuid.UUID, error) {
var userID uuid.UUID
err := r.db.QueryRowContext(ctx, "SELECT id FROM users WHERE name = ?", userName).Scan(&userID)
if err != nil {
return uuid.Nil, fmt.Errorf("select id: %w", err)
}
return userID, nil
}
func (r *Repository) GetUser(ctx context.Context, userID uuid.UUID) (*User, error) {
var user User
if err := r.db.GetContext(ctx, &user, "SELECT id, name, created_at FROM users WHERE id = ?", userID); err != nil {
return nil, fmt.Errorf("select user: %w", err)
}
return &user, nil
}
func (r *Repository) CreateUserByUserID(ctx context.Context, params CreateUserByIDParams) error {
if _, err := r.db.ExecContext(ctx, "INSERT INTO users (id, name, password) VALUES (?, ?, ?)", params.ID, params.ID, "test"); err != nil {
return fmt.Errorf("insert user: %w", err)
}
return nil
}
func (r *Repository) ResetUsers() error {
err := migration.ResetUserTable(r.db.DB)
if err != nil {
return err
}
return nil
}
|
<!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>Transform with Rotate</title>
</head>
<style>
.container {
width: 1000px;
background: grey;
}
.container .move {
width: 150px;
height: 60px;
background: red;
color: white;
font-size: 20px;
margin: 20px 0;
text-align: center;
line-height: 60px;
}
#rotate:hover {
transform: rotate(45deg);
}
#rotatex:hover {
transform: rotateX(45deg);
}
#rotatey:hover {
transform: rotateY(60deg);
}
img {
width: 300px;
display: block;
margin: auto;
transition: transform 2s;
}
img:hover {
/* transform: rotate(45deg); */
/* transform: rotate(90deg); */
/* transform: rotateX(90deg); */
/* transform: rotateY(90deg); */
/* transform: rotate(1turn); */
transform: rotateY(45deg);
}
</style>
<body>
<div class="container">
<div id="rotate" class="move">Rotate Me</div>
</div>
<div class="container">
<div id="rotatex" class="move">Rotate X</div>
</div>
<div class="container">
<div id="rotatey" class="move">Rotate Y</div>
</div>
<hr />
<img src="./img/dog.jpg" alt="" />
</body>
</html>
|
import { InMemoryUsersRepository } from "../../repositories/in-memory/InMemoryUsersRepository";
import { CreateUserUseCase } from "../createUser/CreateUserUseCase"
import { AuthenticateUserUseCase } from "./AuthenticateUserUseCase";
import { IncorrectEmailOrPasswordError } from "./IncorrectEmailOrPasswordError";
let authenticateUserUseCase: AuthenticateUserUseCase;
let createUserUseCase: CreateUserUseCase;
let usersRepositoryInMemory: InMemoryUsersRepository;
describe("Authenticate a User", () => {
beforeEach(() => {
usersRepositoryInMemory = new InMemoryUsersRepository();
createUserUseCase = new CreateUserUseCase(usersRepositoryInMemory);
authenticateUserUseCase = new AuthenticateUserUseCase(usersRepositoryInMemory)
});
it("Should be able to authenticate a user", async () => {
await createUserUseCase.execute({
name: "User Test",
email: "user@test.com.br",
password: "12345",
});
const token = await authenticateUserUseCase.execute({email: "user@test.com.br", password: "12345"});
expect(token).toHaveProperty("token");
});
it("Should not be able authenticate if email is incorrect ", async () => {
expect(async() => {
await createUserUseCase.execute({
name: "User Test",
email: "user@test.com.br",
password: "12345",
});
const authentication = await authenticateUserUseCase.execute({email: "user@testt.com.br", password: "12345"});
}).rejects.toBeInstanceOf(IncorrectEmailOrPasswordError);
});
it("Should not be able authenticate if password is incorrect ", async () => {
expect(async() => {
await createUserUseCase.execute({
name: "User Test",
email: "user@test.com.br",
password: "12345",
});
const authentication = await authenticateUserUseCase.execute({email: "user@test.com.br", password: "123"});
}).rejects.toBeInstanceOf(IncorrectEmailOrPasswordError);
});
});
|
---
title: Add authentication
id: embedded-sdk-add-authentication
description: ""
slug: /embedded-sdk-add-authentication
keywords:
- scenario
pagination_next: null
pagination_prev: null
last_update:
date: 08/25/2023
author: Jen Field
draft: false
hide_table_of_contents: false
hide_title: false
hide_breadcrumbs: false
doc_type: quickstart
displayed_sidebar: mainSidebar
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import WebAuth from "../includes/_authentication-via-automatic.mdx";
import SilentAuth from "../includes/_authentication-via-return.mdx";
import MultiLanguageCodeBlock from "@site/src/components/CodeBlocks/MultiLanguageCodeBlock";
import InvocationDiagram from "../includes/_invocation-url-diagram.mdx";
import AppSchemeCaution from "../includes/_app-scheme-caution.mdx";
import InvocationTip from "../includes/_invocation-type-tip.mdx";
import ProtocolOIDC from '../includes/_protocol_oidc.mdx';
import PKCES256 from '../includes/_pkce_s256.mdx';
import ScopeOpenid from '../includes/_scope_openid.mdx';
import HostedWeb from '../includes/_hosted-web.mdx';
import ClientTypeConfidential from '../includes/_client-type_confidential.mdx';
import GrantTypeAuthorizationCode from '../includes/_grant-type_authorization-code.mdx';
import TokenEndpointAuthMethodClientSecretBasic from '../includes/_token-endpoint-auth-method_client-secret-basic.mdx';
import HWADiagram from '../includes/_hwa-diagram.mdx';
import OIDCLibrary from '../includes/_configure_oidc_client_library.mdx';
import { Alert, Col, Row } from "antd";
This guide describes how to add authentication to your application using the Beyond Identity Embedded SDK and a standard OAuth2/OIDC flow.
The OAuth2/OIDC calls can be set up using an OpenID Connect client library. Many frameworks and languages have their own.
If you wish to find an OpenID Connect client, we recommend looking for one on the list of [certified OpenID Connect clients](https://openid.net/developers/certified/).
In response to an OIDC request to the Beyond Identity `/authorize` endpoint, Beyond Identity initiates passwordless authentication by returning an authentication challenge and other information to your app. Before authenticating, your app can use the Beyond Identity SDK to enumerate available passkeys and should perform some logic to select one, such as presenting selection UI to the user. Once a passkey is selected, you can then use the SDK to complete authentication and finally perform the OAuth code for token exchange.
## Overview
With this guide you will:
1. Create a Beyond Identity application using the Embedded SDK configuration type.
2. Configure an OpenID Connect client library or build your own OIDC calls.
3. Invoke and consume Beyond Identity authentication calls in your app using the Embedded SDK.
## Create your Beyond Identity application
### Prerequisites
- [x] A [developer account](https://www.beyondidentity.com/developers)
- [x] Logged into your admin console
Depending on the region you chose when you signed up, you can access the Beyond Identity admin console for your tenant at:
- [BI admin console US](https://console-us.beyondidentity.com/login)
- [BI admin console EU](https://console-eu.beyondidentity.com/login)
:::tip
_If you are signing in from a different computer or browser, you can enter the email address you used when you signed up. Beyond Identity will send you a one time link you can use to sign in and enroll a passkey from the new browser._
:::
### Create a new realm
So far, you have the Beyond Identity Admin Realm for your Beyond Identity tenant only. In this step, you'll create a new Realm to hold your users' identities and the configuration.
import CreateRealmConsole from '../includes/_create-realm-console.mdx';
<CreateRealmConsole />
### Create an application
In this step, you'll create a new Application containing the configuration for your users.
import AddAppAdminConsole from '../includes/_add-application-console.mdx';
<AddAppAdminConsole />
On the **External Protocol** tab, use the following values to complete this tab.
| Property | Value |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Display Name** | Descriptive name you choose |
| **Protocol** | OIDC<br /><ProtocolOIDC/> |
| **Client Type** | Confidential<br /><ClientTypeConfidential/> |
| **PKCE** | S256<br /><PKCES256/> |
| **Redirect URIs** | Use a route in your app that is capable of handling the authorization code exchange.<br /><br />If you are using an OpenID Connect client library, a redirect URI may be specified for you. <br /><br />For example: In a Next.js application using NextAuth, your redirect URI follows the pattern:<br /><br /><pre>http://localhost:3000/api/auth/callback/beyondidentity</pre><div class= "note-message note-message-table"><p>where `beyondidentity` in this URI is the ID of the Auth provider as configured in the providers array in NextAuth.js and `/api/auth/callback/` is based on the Next.js route file structure.</p></div> |
| **Token Endpoint Auth Method** | Client Secret Basic<br /><TokenEndpointAuthMethodClientSecretBasic/> |
| **Grant Type** | Authorization Code<br /><GrantTypeAuthorizationCode/> |
| **All other options** | Use the default values for the remaining options |
On the **Authenticator Config** tab, use the following values to complete this tab.
| Property | Value |
| -------------------------- | ---------------------------------------------------- |
| **Configuration Type** | Embedded SDK |
| **Invocation Type** | In the case of a web application, this is just a URL to your web application such as 'http://localhost:3000'. <br />In the case of a native application (iOS, Android, Flutter, React Native), this is either an App Scheme or a Universal URL / App Link.<br/> <div class= "note-message note-message-table"><p>While app schemes are generally easier to set up, Universal URLs and App Links are recommended as they provide protection against App Scheme hijacking.</p></div>|
| **Trusted Origins** | Enter your app's hostname and port, such as 'http://localhost:3000' |
:::tip **CHECKPOINT**
Congrats!
You've created and configured a Beyond Identity application. You're now ready to use the values from this applications for your OpenID Connect client.
:::
## Configure an OpenID Connect client library
<OIDCLibrary />
## Craft your own authorization request
If you are not using a library, you will need to configure your own authorization and token calls using the **Authorization Endpoint** and **Token Endpoint** found in your application's **External Protocol** tab.
Crafting an authorization URL is the first step in the authorization flow.
1. In the Admin Console, under Apps, select the **External Protocol** tab, copy the **Authorization Endpoint** value and add it to the query parameters:

```bash title="/authorize"
https://auth-$REGION.beyondidentity.com/v1/tenants/$TENANT_ID/realms/$REALM_ID/applications/$APPLICATION_ID/authorize?
response_type=code
&client_id=$CLIENT_ID
&redirect_uri=$REDIRECT_URI
&scope=openid
&state=$STATE
&code_challenge_method=256
&code_challenge=$PKCE_CODE_CHALLENGE
```
| Parameter | Value |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **response_type** | code <br /><br />This parameter specifies that the authorization server should return an authorization code to the client. The code will be used by the client to request an access token.<div class= "note-message note-message-table"><p>**Grant Type** must be set to **Authorization Code** in the console application. </p></div> |
| **client_id** | Copy and paste the **Client ID** value from your application's **External Protocol** tab. |
| **redirect_uri** | This parameter specifies the URL to which the authorization server can send an authorization code. If a state parameter was specified in the /authorize request, then that will be echoed back to this URL as well.<br /><br /><div class= "note-message note-message-table"><p>This must match one of the **Redirect URIs** registered in your console application.</p></div> |
| **scope** | openid <ScopeOpenid/> |
| **state** | This parameter is a random value generated by the client. It is included in the authorization request and returned in the response. This parameter helps the client maintain state between the request and the callback to prevent cross-site request forgery (CSRF) attacks. |
| **code_challenge_method** | 256 <br /><PKCES256/><div class= "note-message note-message-table"><p>This value is optional. **PKCE** must be enabled to **S256** in the console application. If it is not enabled then you should not send the **code_challenge_method** or **code_challenge** parameters.</p></div> |
| **code_challenge** | This used in conjunction with **code_challenge_method** ensures that the authorization code obtained by the client can only be used by the client that originally requested it.<br /><br />You will need to store the hash of the **code_challenge** so that it can be passed to the token exchange endpoint later as a **code_verifier**.<br /><br /><div class= "note-message note-message-table"><p>This value is optional. **PKCE** must be enabled in the console application. If it is not enabled then you should not send the **code_challenge_method** or **code_challenge** parameters.</p></div> |
:::tip
The **code_challenge** is generated as defined in [**RFC 7636**](https://datatracker.ietf.org/doc/html/rfc7636#section-4.2), example JavaScript snippet below:
```javascript
codeVerifier = crypto.randomBytes(32).toString('base64url');
codeChallenge = crypto
.createHash('sha256')
.update(codeVerifier)
.digest()
.toString('base64url');
```
:::
2. Start authorization for Invocation Type.
<Tabs groupId="authenticate-invocation-type" queryString>
<TabItem value="manual" label="Manual">
<SilentAuth />
</TabItem>
<TabItem value="automatic" label="Automatic">
<WebAuth />
</TabItem>
</Tabs>
## Call the token endpoint for token exchange
The [authenticate call returns](/docs/embedded-reference-authenticate#returns) an object that contains a **redirectURL** to which your app should redirect the user to complete the OIDC flow.
Keeping with the OIDC specifications, this URL includes the **code** and **state** parameters as query parameters.
Calling the `/token` endpoint is the second step in the authorization flow. In this call, your app sends the **code** as part of an OAuth call to exchange it for an [access token](/docs/terms/access-token.md) and [id token](/docs/terms/id-token.md).
1. Click the **External Protocol** tab and copy the **Token Endpoint**.
2. Scroll down to **Client Configuration** and make a note of the **Token Endpoint Auth Method** selected. It determines how to make the token exchange call.
- **Client Secret Post**
- **Client Secret Basic**
3. <a name="token-exchange"></a>Start the token exchange.
<Tabs groupId="token-auth-method" queryString>
<TabItem value="client_secret_basic" label="Client Secret Basic">
The `$CLIENT_ID` and `$CLIENT_SECRET` are sent in the Basic Authorization header.
<MultiLanguageCodeBlock
curl='curl "https://auth-$(REGION).beyondidentity.com/v1/tenants/$(TENANT_ID)/realms/$(REALM_ID)/applications/$(APPLICATION_ID)/token" \
-X POST \
-u "$(CLIENT_ID):$(CLIENT_SECRET)" --basic \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code&code=$(CODE_FROM_AUTHORIZATION_RESPONSE)&code_verifier=$(CODE_VERIFIER_IF_USED_PKCE_IN_AUTHORIZATION_REQUEST)&redirect_uri=$(REDIRECT_URI_MUST_MATCH_VALUE_USED_IN_AUTHORIZATION_REQUEST)"'
title="/token"
/>
</TabItem>
<TabItem value="client_secret_post" label="Client Secret Post">
The `$CLIENT_ID` and `$CLIENT_SECRET` are sent in the body of the POST request as a form parameter.
<MultiLanguageCodeBlock
curl='curl "https://auth-$(REGION).beyondidentity.com/v1/tenants/$(TENANT_ID)/realms/$(REALM_ID)/applications/$(APPLICATION_ID)/token" \
-X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-F "grant_type=authorization_code" \
-F "code=$(CODE_FROM_AUTHORIZATION_RESPONSE)" \
-F "client_id=$(CLIENT_ID)" \
-F "client_secret=$(CLIENT_SECRET_FROM_CONFIDENTIAL_APPLICATION)" \
-F "code_verifier=$(CODE_VERIFIER_IF_USED_PKCE_IN_AUTHORIZATION_REQUEST)" \
-F "redirect_uri=$(REDIRECT_URI_MUST_MATCH_VALUE_USED_IN_AUTHORIZATION_REQUEST)"'
title="/token"
/>
</TabItem>
</Tabs>
|
using API.Extensions;
using Core.Helpers;
using Core.Interfaces;
using Microsoft.AspNetCore.Mvc;
using API.Helpers;
using Newtonsoft.Json.Linq;
using API.DTOs;
using Newtonsoft.Json;
using System.Text;
namespace API.Controllers
{
public class CompaniesController : BaseApiController
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
public CompaniesController(IHttpClientFactory httpClientFactory, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_configuration = configuration;
}
[Cached(60*24)]
[HttpGet("{ticker}")]
public async Task<ActionResult<CompanyInfo>> GetCompanyWithTicker(string ticker)
{
var token = _configuration["TiingoSettings:Token"];
var requestUrl = $"/iex/{ticker}?token={token}";
var httpClient = _httpClientFactory.CreateClient("TiingoClient");
var response = await httpClient.GetAsync(requestUrl);
if (!response.IsSuccessStatusCode)
{
return BadRequest();
}
string responseBody = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(responseBody)) return BadRequest();
var jsonData = JArray.Parse(responseBody);
string jsonString = jsonData[0].ToString();
CompanyInfo companyInfo = JsonConvert.DeserializeObject<CompanyInfo>(jsonString);
return Ok(companyInfo);
}
[Cached(60*24)]
[HttpGet("daily/{ticker}")]
public async Task<ActionResult<List<DailyData>>> GetFundamentalsDailyData
([FromRoute] string ticker, [FromQuery] DailyParams dailyParams)
{
var token = _configuration["TiingoSettings:Token"];
StringBuilder requestUrlBuilder = new StringBuilder($"/tiingo/fundamentals/{ticker}/daily?token={token}");
if (dailyParams.StartDate.HasValue)
{
requestUrlBuilder.Append($"&startDate={dailyParams.StartDate.Value:yyyy-MM-ddTHH:mm:ss.fffZ}");
}
if (dailyParams.EndDate.HasValue)
{
requestUrlBuilder.Append($"&endDate={dailyParams.EndDate.Value:yyyy-MM-ddTHH:mm:ss.fffZ}");
}
var requestUrl = requestUrlBuilder.ToString();
var httpClient = _httpClientFactory.CreateClient("TiingoClient");
var response = await httpClient.GetAsync(requestUrl);
if (!response.IsSuccessStatusCode)
{
return BadRequest();
}
string responseBody = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(responseBody)) return BadRequest();
var jsonData = JArray.Parse(responseBody);
string jsonString = jsonData.ToString();
var fundamentalsDailyData = JsonConvert.DeserializeObject<List<DailyData>>(jsonString);
return Ok(fundamentalsDailyData);
}
[Cached(60*24)]
[HttpGet("meta/{ticker}")]
public async Task<ActionResult<Meta>> GetMeta(string ticker)
{
var token = _configuration["TiingoSettings:Token"];
var requestUrl = $"/tiingo/fundamentals/meta?tickers={ticker}&token={token}";
var httpClient = _httpClientFactory.CreateClient("TiingoClient");
var response = await httpClient.GetAsync(requestUrl);
if (!response.IsSuccessStatusCode)
{
return BadRequest();
}
string responseBody = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(responseBody)) return BadRequest();
var jsonData = JArray.Parse(responseBody);
string jsonString = jsonData[0].ToString();
var fundamentalsMetaData = JsonConvert.DeserializeObject<Meta>(jsonString);
return Ok(fundamentalsMetaData);
}
[Cached(60*24)]
[HttpGet("interday-prices/{ticker}")]
public async Task<ActionResult<List<InterdayPrice>>> GetHistoricalIntradayPricesEndpoint
([FromRoute] string ticker, [FromQuery] InterdayPriceParams interdayParams)
{
var token = _configuration["TiingoSettings:Token"];
StringBuilder requestUrlBuilder = new StringBuilder($"/iex/{ticker}/prices?token={token}");
if (interdayParams.StartDate.HasValue)
{
requestUrlBuilder.Append($"&startDate={interdayParams.StartDate.Value}");
}
if (interdayParams.EndDate.HasValue)
{
requestUrlBuilder.Append($"&endDate={interdayParams.EndDate.Value}");
}
requestUrlBuilder.Append($"&requestFreq={interdayParams.RequestFreq}");
var requestUrl = requestUrlBuilder.ToString();
var httpClient = _httpClientFactory.CreateClient("TiingoClient");
var response = await httpClient.GetAsync(requestUrl);
if (!response.IsSuccessStatusCode)
{
return BadRequest();
}
string responseBody = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(responseBody)) return BadRequest();
var jsonData = JArray.Parse(responseBody);
string jsonString = jsonData.ToString();
var interdayPrices = JsonConvert.DeserializeObject<List<InterdayPrice>>(jsonString);
return Ok(interdayPrices);
}
[Cached(60*24)]
[HttpGet("dividend-yield/{ticker}")]
public async Task<ActionResult<List<DividendYield>>> GetDividendYield
([FromRoute] string ticker)
{
var token = _configuration["TiingoSettings:Token"];
var requestUrl = $"/tiingo/corporate-actions/{ticker}/distribution-yield?token={token}";
var httpClient = _httpClientFactory.CreateClient("TiingoClient");
var response = await httpClient.GetAsync(requestUrl);
if (!response.IsSuccessStatusCode)
{
return BadRequest();
}
string responseBody = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(responseBody)) return BadRequest();
var jsonData = JArray.Parse(responseBody);
string jsonString = jsonData.ToString();
var dividendYields = JsonConvert.DeserializeObject<List<DividendYield>>(jsonString);
if (dividendYields.Count == 0) {
return BadRequest("There are no dividend yields");
}
var lastDividend = dividendYields.Last();
return Ok(lastDividend);
}
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "concur-hash.h"
// hash
/* this is the D. J. Bernstein hash function */
static unsigned int djb_hash(const char *cp) {
unsigned hash = 5381;
while(*cp)
hash = 33 * hash ^ (unsigned char) *cp++;
return hash;
}
void hash_init(hash_t *ht, int num_buckets){
pthread_mutex_init(&ht->mu, 0);
ht->buckets = calloc(num_buckets, sizeof (*ht->buckets));
ht->num_buckets = num_buckets;
}
void hash_insert(hash_t *ht, char *key, char *value) {
// Exercise 2: complete the code below:
// Add your code here:
pthread_mutex_lock(&ht->mu);
unsigned int hash = djb_hash(key) % ht->num_buckets;
node_t *newNode = malloc(sizeof(node_t));
if (newNode == NULL) {
printf("failed to creat new Node!");
pthread_mutex_unlock(&ht->mu);
}
newNode->key = strdup(key);
newNode->value = strdup(value);
newNode->next = ht->buckets[hash];
ht->buckets[hash] = newNode;
pthread_mutex_unlock(&ht->mu);
}
char *hash_lookup(hash_t *ht, char *key) {
pthread_mutex_lock(&ht->mu);
unsigned int hash = djb_hash(key) % ht->num_buckets;
node_t *bucket = ht->buckets[hash];
while (bucket && strcmp(key, bucket->key) != 0) {
bucket = bucket->next;
}
char *val = NULL;
if (bucket != NULL) {
val = bucket->value;
}
pthread_mutex_unlock(&ht->mu);
return val;
}
// return 0 for success; 1 for non-exiting "key"
int hash_delete(hash_t *ht, char *key){
pthread_mutex_lock(&ht->mu);
unsigned int hash = djb_hash(key) % ht->num_buckets;
node_t *pNode = ht->buckets[hash];
node_t *last = pNode;
while (pNode && strcmp(key, pNode->key) != 0) {
last = pNode;
pNode = pNode->next;
}
if (pNode == NULL) {
return 1;
}
// deleting the matching node
if (last == pNode) {
ht->buckets[hash] = NULL;
} else {
last->next = pNode->next;
}
free(pNode);
pthread_mutex_unlock(&ht->mu);
return 0;
}
int hash_size(hash_t *ht){
int size = 0;
// Exercise 2: complete the code below:
// Add your code here:
pthread_mutex_lock(&ht->mu);
for (int i = 0; i < ht->num_buckets; i++) {
node_t *pNode = ht->buckets[i];
while (pNode) {
size++;
pNode = pNode->next;
}
}
pthread_mutex_unlock(&ht->mu);
return size;
}
|
#![no_std]
#![no_main]
// choice of Board Support Package
use rp_pico as bsp;
use bsp::entry;
use bsp::hal::{
self,
clocks::{init_clocks_and_plls, Clock},
pac::{self, interrupt},
gpio,
sio,
watchdog
};
use cortex_m as cpu;
use cortex_m::interrupt::Mutex;
use ehal::digital::v2::{InputPin, OutputPin, PinState};
use core::convert::Infallible;
use core::panic::PanicInfo;
use core::cell::Cell;
use heapless::Vec;
use usb_device::{
prelude::*,
class_prelude::*,
};
use usbd_hid::{
hid_class, descriptor::generator_prelude::*
};
use keeb::{
prelude::*,
Error,
layout::{Keymap},
board::{Board},
bus::{TryIntoInputPin, TryIntoOutputPin},
usb::NKROBootKeyboardReport,
switch_matrix::SwitchMatrix,
led_matrix::LedMatrix,
vkeyboard::VKeyboard,
};
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
// set panic led
set_led(true);
hal::halt();
}
fn set_led(state: bool) {
cpu::interrupt::free(|cs| {
let mut led_pin = Cell::new(None);
mutex_led_pin.borrow(cs).swap(&led_pin);
match led_pin.get_mut() {
Some(pin) => {
if state {
pin.set_high().unwrap();
}
else {
pin.set_low().unwrap();
}
},
_ => {}
}
mutex_led_pin.borrow(cs).swap(&led_pin);
});
}
type PinOut = gpio::FunctionSio<gpio::SioOutput>;
type PinIn = gpio::FunctionSio<gpio::SioInput>;
type PinPD = gpio::PullDown;
struct GpioIn {
pin: gpio::Pin<gpio::DynPinId, PinIn, PinPD>
}
impl GpioIn {
fn new<I: gpio::PinId, F: gpio::Function, P: gpio::PullType>(
pin: gpio::Pin<I, F, P>) -> Self
where I: gpio::ValidFunction<PinIn> {
Self {
pin: pin.into_pull_down_input().into_dyn_pin()
}
}
}
struct GpioOut {
pin: gpio::Pin<gpio::DynPinId, PinOut, PinPD>
}
impl GpioOut {
fn new<I: gpio::PinId, F: gpio::Function, P: gpio::PullType>(
pin: gpio::Pin<I, F, P>) -> Self
where I: gpio::ValidFunction<PinOut> {
Self {
pin: pin.into_push_pull_output().into_pull_type().into_dyn_pin()
}
}
}
impl InputPin for GpioIn {
type Error = Infallible;
fn is_high(&self) -> Result<bool, Self::Error> {
self.pin.is_high()
}
fn is_low(&self) -> Result<bool, Self::Error> {
self.pin.is_low()
}
}
impl TryIntoOutputPin for GpioIn {
type Pin = GpioOut;
fn try_into_output_pin(self) -> Result<Self::Pin, Error> {
match self.pin.try_into_function::<PinOut>() {
Ok(pin) => Ok(Self::Pin { pin: pin }),
Err(_) => Err(Error::PinConfigError)
}
}
}
impl OutputPin for GpioOut {
type Error = Infallible;
fn set_low(&mut self) -> Result<(), Self::Error> {
self.pin.set_low()
}
fn set_high(&mut self) -> Result<(), Self::Error> {
self.pin.set_high()
}
}
impl TryIntoInputPin for GpioOut {
type Pin = GpioIn;
fn try_into_input_pin(self) -> Result<Self::Pin, Error> {
match self.pin.try_into_function::<PinIn>() {
Ok(pin) => Ok(Self::Pin { pin: pin }),
Err(_) => Err(Error::PinConfigError)
}
}
}
struct UserPins {
led: GpioOut,
general_pins: Vec<GpioIn, 32>,
general_ids: Vec<usize, 32>,
}
fn into_user_pins(pins: bsp::Pins) -> UserPins {
UserPins {
led: GpioOut::new(pins.led),
general_pins: [
GpioIn::new(pins.gpio0),
GpioIn::new(pins.gpio1),
GpioIn::new(pins.gpio2),
GpioIn::new(pins.gpio3),
GpioIn::new(pins.gpio4),
GpioIn::new(pins.gpio5),
GpioIn::new(pins.gpio6),
GpioIn::new(pins.gpio7),
GpioIn::new(pins.gpio8),
GpioIn::new(pins.gpio9),
GpioIn::new(pins.gpio10),
GpioIn::new(pins.gpio11),
GpioIn::new(pins.gpio12),
GpioIn::new(pins.gpio13),
GpioIn::new(pins.gpio14),
GpioIn::new(pins.gpio15),
GpioIn::new(pins.gpio16),
GpioIn::new(pins.gpio17),
GpioIn::new(pins.gpio18),
GpioIn::new(pins.gpio19),
GpioIn::new(pins.gpio20),
GpioIn::new(pins.gpio21),
GpioIn::new(pins.gpio22),
GpioIn::new(pins.gpio26),
GpioIn::new(pins.gpio27),
GpioIn::new(pins.gpio28),
].into_iter().collect(),
general_ids: [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 26, 27, 28
].into_iter().collect(),
}
}
type UsbBusAlloc = UsbBusAllocator<hal::usb::UsbBus>;
type UsbDev<'a> = UsbDevice<'a, hal::usb::UsbBus>;
type UsbKbdClass<'a> = hid_class::HIDClass<'a, hal::usb::UsbBus>;
struct UsbInterface<'a> {
usb_dev: UsbDev<'a>,
usb_kbd_class: UsbKbdClass<'a>,
}
static mutex_usb_interface: Mutex<Cell<Option<UsbInterface>>>
= Mutex::new(Cell::new(None));
static mutex_led_pin: Mutex<Cell<Option<GpioOut>>>
= Mutex::new(Cell::new(None));
#[allow(non_snake_case)]
#[interrupt]
unsafe fn USBCTRL_IRQ() {
cpu::interrupt::free(|cs| {
let mut usb_interface = Cell::new(None);
mutex_usb_interface.borrow(cs).swap(&usb_interface);
match usb_interface.get_mut() {
Some(UsbInterface{ usb_dev, usb_kbd_class, .. }) => {
usb_dev.poll(&mut [usb_kbd_class]);
},
_ => {}
}
mutex_usb_interface.borrow(cs).swap(&usb_interface);
});
}
// generic keyboard
// https://github.com/obdev/v-usb/blob/master/usbdrv/USB-IDs-for-free.txt
const USB_VID_PID_GEN_KBD: UsbVidPid = UsbVidPid(0x16c0, 0x27db);
// USB poll bInterval [1-255]
const USB_POLL_MS: u8 = 1;
#[entry]
fn rp2040_main() -> ! {
// usb bus must be static lifetime for interrupts
static mut USB_BUS: Option<UsbBusAlloc> = None;
// init board state and components
let mut pac = pac::Peripherals::take().unwrap();
let core = pac::CorePeripherals::take().unwrap();
let mut watchdog = watchdog::Watchdog::new(pac.WATCHDOG);
let sio = sio::Sio::new(pac.SIO);
const XTAL_FREQ_HZ: u32 = 12_000_000_u32;
let clocks = init_clocks_and_plls(
XTAL_FREQ_HZ, pac.XOSC, pac.CLOCKS, pac.PLL_SYS, pac.PLL_USB,
&mut pac.RESETS, &mut watchdog).ok().unwrap();
let mut delay = cpu::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz());
let pins = bsp::Pins::new(
pac.IO_BANK0,
pac.PADS_BANK0,
sio.gpio_bank0,
&mut pac.RESETS,
);
// set up USB
*USB_BUS = Some(UsbBusAllocator::new(hal::usb::UsbBus::new(
pac.USBCTRL_REGS, pac.USBCTRL_DPRAM, clocks.usb_clock, true, &mut pac.RESETS
)));
let usb_bus = USB_BUS.as_ref().unwrap();
let desc = NKROBootKeyboardReport::desc();
let usb_kbd_class = hid_class::HIDClass::new_with_settings(
&usb_bus, desc, USB_POLL_MS,
hid_class::HidClassSettings {
subclass: hid_class::HidSubClass::NoSubClass,
protocol: hid_class::HidProtocol::Keyboard,
config: hid_class::ProtocolModeConfig::DefaultBehavior,
locale: hid_class::HidCountryCode::US,
});
let usb_dev =
UsbDeviceBuilder::new(&usb_bus, USB_VID_PID_GEN_KBD)
.manufacturer("gkanwar")
.product("Unchat-42")
.serial_number("XXXX")
.build();
// TODO: OSX doesn't recognize keyboard when HID device class is set
// .device_class(USB_CLASS_HID)
let usb_interface = Cell::new(Some(UsbInterface {
usb_dev, usb_kbd_class
}));
cpu::interrupt::free(|cs| {
mutex_usb_interface.borrow(cs).swap(&usb_interface);
});
// USB interrupts
unsafe {
pac::NVIC::unmask(pac::Interrupt::USBCTRL_IRQ);
}
// load keymap
let (keymap, _bytes_read): (Keymap, usize) =
serde_json::from_slice(include_bytes!("../../keymaps/split-42-colemak.json"))
.unwrap();
let layout = keeb::layout::get_layout(keymap.layout);
// load board
let (board, _bytes_read): (Board, usize) =
serde_json::from_slice(include_bytes!("../../boards/unchat-42.json"))
.unwrap();
let user_pins = into_user_pins(pins);
let led_pin = Cell::new(Some(user_pins.led));
cpu::interrupt::free(|cs| {
mutex_led_pin.borrow(cs).swap(&led_pin);
});
let mut general_pins = user_pins.general_pins;
let mut general_ids = user_pins.general_ids;
let board_pins =
keeb::board::split_pins(general_pins, general_ids, &board).unwrap();
let (mut in_bus, mut bus_lock) =
keeb::bus::make_bus(board_pins.bus_pins);
let reg_map = keeb::board::make_reg_map(&board, &layout);
let mut switches = SwitchMatrix::<GpioOut>::new(
reg_map.clone(), board_pins.switch_reg_pins).unwrap();
let mut leds = LedMatrix::<GpioOut>::new(
reg_map,
board_pins.backlight_reg_pins,
board_pins.backlight_reset_pin,
board_pins.backlight_dim_pin);
let mut vkbd = VKeyboard::new(keymap).unwrap();
let mut buf: [u8; 64] = [0; 64]; // for usb OUT packets
let mut pending = false;
loop {
delay.delay_ms(1);
let (updated, new_in_bus, new_bus_lock) = keeb::tick(
in_bus, bus_lock, &mut switches, &mut leds, &mut vkbd, &mut delay
).unwrap();
in_bus = new_in_bus;
bus_lock = new_bus_lock;
if vkbd.reset {
hal::rom_data::reset_to_usb_boot(0, 0);
}
if !updated && !pending {
continue;
}
let mut report = vkbd.get_report().clone();
cpu::interrupt::free(|cs| {
let mut usb_interface = Cell::new(None);
mutex_usb_interface.borrow(cs).swap(&usb_interface);
let configured = match usb_interface.get_mut() {
Some(UsbInterface{ usb_dev, .. }) =>
usb_dev.state() == UsbDeviceState::Configured,
None => false,
};
if configured {
match usb_interface.get_mut() {
Some(UsbInterface{ usb_kbd_class, .. }) => {
match usb_kbd_class.pull_raw_output(&mut buf) {
Ok(size) => {},
Err(UsbError::WouldBlock) => {}, // no data
Err(err) => panic!("unexpected read error"),
}
match usb_kbd_class.get_protocol_mode() {
Ok(hid_class::HidProtocolMode::Report) => {
for i in 0..report.boot_keys.len() {
report.boot_keys[i] = 0;
}
}
_ => {}
}
match usb_kbd_class.push_input(&report) {
Ok(size) => {
pending = false;
},
Err(UsbError::WouldBlock) => { // buffer full
pending = true;
},
// usbd-hid bug: error on protocol `Report` with subclass `Boot`
// hack: forcibly set protocol mode to Boot :(
Err(UsbError::InvalidState) => {
pending = true;
let protocol = usb_kbd_class.get_protocol_mode();
if let Ok(protocol) = protocol {
usb_kbd_class.set_protocol_mode(
protocol, hid_class::ProtocolModeConfig::ForceBoot).unwrap();
}
},
Err(err) => panic!("unexpected write error"),
}
},
None => {},
}
}
mutex_usb_interface.borrow(cs).swap(&usb_interface);
});
}
// pause, then reboot into BOOTSEL
delay.delay_ms(1000);
hal::rom_data::reset_to_usb_boot(0, 0);
unreachable!();
}
|
import { Navigate, Route, Routes } from "react-router-dom";
import HomePage from "./pages/home-page";
import CreateWorkoutPage from "./pages/create-workout-page";
import { QueryClient, QueryClientProvider } from "react-query";
import ViewWorkoutPage from "./pages/view-workout-page";
import EditWorkoutPage from "./pages/edit-workout-page";
import Login from "./pages/login";
import ProtectedRoute from "./components/protected-route";
import TrackerPage from "./pages/tracker-page";
import TrackerWorkoutPage from "./pages/exercise-tracker-page";
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<Routes>
<Route element={<ProtectedRoute />}>
<Route path="/routine" element={<HomePage />} />
<Route path="/create-routine" element={<CreateWorkoutPage />} />
<Route
path="/edit-workout/:workout_id"
element={<EditWorkoutPage />}
/>
<Route path="/tracker" element={<TrackerPage />} />
<Route
path="/tracker/workout/:workout_id"
element={<TrackerWorkoutPage />}
/>
<Route path="/routine/:workout_id" element={<ViewWorkoutPage />} />
</Route>
<Route path="/" element={<Navigate to="routine" />} />
<Route path="/login" element={<Login />} />
</Routes>
</QueryClientProvider>
);
}
export default App;
|
import {
Args,
Mutation,
Parent,
Query,
ResolveField,
Resolver,
} from '@nestjs/graphql';
import DataLoader from 'dataloader';
import { Chaincode } from 'src/chaincode/models/chaincode.model';
import { ChannelLoader } from 'src/channel/channel.loader';
import { Channel } from 'src/channel/models/channel.model';
import { Loader } from 'src/common/dataloader';
import { Auth } from 'src/common/decorators/auth.decorator';
import { K8sV1Status } from 'src/common/models/k8s-v1-status.model';
import { flattenArr, NETWORK_VERSION_RESOURCES } from 'src/common/utils';
import { IbppeerService } from 'src/ibppeer/ibppeer.service';
import { Ibppeer } from 'src/ibppeer/models/ibppeer.model';
import { Organization } from 'src/organization/models/organization.model';
import { OrganizationLoader } from 'src/organization/organization.loader';
import { JwtAuth } from 'src/types';
import { NewNetworkInput } from './dto/new-network.input';
import { OrderVersion } from './dto/order-version.enum';
import { Network } from './models/network.model';
import { NetworkService } from './network.service';
@Resolver(() => Network)
export class NetworkResolver {
constructor(
private readonly networkService: NetworkService,
private readonly peerService: IbppeerService,
) {}
@Query(() => [Network], { description: '网络列表' })
async networks(@Auth() auth: JwtAuth): Promise<Network[]> {
return this.networkService.getNetworks(auth);
}
@Query(() => Network, { description: '网络详情' })
async network(
@Auth() auth: JwtAuth,
@Args('name') name: string,
): Promise<Network> {
return this.networkService.getNetwork(auth, name);
}
@Mutation(() => Network, { description: '创建网络' })
async networkCreate(
@Auth() auth: JwtAuth,
@Args('network') network: NewNetworkInput,
): Promise<Network> {
return this.networkService.createNetwork(auth, network);
}
@Mutation(() => Boolean, {
description:
'释放网络(返回true:只表示这个操作触发成功,而不是释放网络成功)',
})
async networkDissolve(
@Auth() auth: JwtAuth,
@Args('name') name: string,
@Args('federation', { description: '所属联盟' }) federation: string,
): Promise<boolean> {
return this.networkService.dissolveNetwork(auth, name, federation);
}
@Mutation(() => K8sV1Status, { description: '删除网络' })
async networkDelete(
@Auth() auth: JwtAuth,
@Args('name') name: string,
): Promise<K8sV1Status> {
return this.networkService.deleteNetwork(auth, name);
}
@ResolveField(() => OrderVersion, { nullable: true, description: '配置版本' })
version(@Parent() network: Network): OrderVersion {
const { storage } = network;
if (NETWORK_VERSION_RESOURCES[OrderVersion.Enterprise][4] === storage) {
return OrderVersion.Enterprise;
}
if (NETWORK_VERSION_RESOURCES[OrderVersion.Finance][4] === storage) {
return OrderVersion.Finance;
}
if (NETWORK_VERSION_RESOURCES[OrderVersion.Standard][4] === storage) {
return OrderVersion.Standard;
}
return null;
}
@ResolveField(() => [Organization], { description: '组织' })
async organizations(
@Parent() network: Network,
@Loader(OrganizationLoader)
organizationLoader: DataLoader<Organization['name'], Organization>,
): Promise<Organization[]> {
const { members } = network;
if (!members) return [];
const orgs = await organizationLoader.loadMany(
members.map((member) => member.name),
);
return orgs as Organization[];
}
@ResolveField(() => Organization, {
nullable: true,
description: '网络发起者(组织)',
})
async initiator(
@Parent() network: Network,
@Loader(OrganizationLoader)
organizationLoader: DataLoader<Organization['name'], Organization>,
): Promise<Organization> {
const { initiatorName } = network;
if (!initiatorName) return;
const org = await organizationLoader.load(initiatorName);
return org;
}
@ResolveField(() => [Channel], { nullable: true, description: '通道列表' })
async channels(
@Parent() network: Network,
@Loader(ChannelLoader) channelLoader: DataLoader<Channel['name'], Channel>,
): Promise<Channel[]> {
const { channelNames } = network;
if (!channelNames || channelNames.length === 0) return;
const cs = await channelLoader.loadMany(channelNames);
return cs;
}
@ResolveField(() => [Ibppeer], {
nullable: true,
description: '网络中的所有节点',
})
async peers(
@Auth() auth: JwtAuth,
@Parent() network: Network,
@Loader(ChannelLoader) channelLoader: DataLoader<Channel['name'], Channel>,
): Promise<Ibppeer[]> {
const { channelNames } = network;
if (!channelNames || channelNames.length === 0) return;
const channels = await channelLoader.loadMany(channelNames);
const peerses = (channels as Channel[])?.map((channel) => channel.peers);
const peers = flattenArr(peerses);
// TODO: IbppeerLoader, 以namespace/name为key
return Promise.all(
peers?.map((peer) =>
this.peerService
.getIbppeer(auth, peer.namespace, peer.name)
.catch(() => peer),
),
);
}
@ResolveField(() => [Chaincode], {
nullable: true,
description: '智能合约',
})
async chaincode(
@Auth() auth: JwtAuth,
@Parent() network: Network,
): Promise<Chaincode[]> {
const { name } = network;
return this.networkService.getResolveFieldChaincode(auth, name);
}
}
|
import {
fireEvent,
render,
screen,
waitFor,
} from '../../../../test-utils/testing-library-utils';
import userEvent from '@testing-library/user-event';
import { RegisterCard } from '../RegisterCard';
import { toast } from 'react-toastify';
import { useNavigate } from 'react-router-dom';
import AddItemCard from '../AddItemCard';
// const axiosPostSpy = jest.spyOn(axios, 'post');
const mockNavigate = jest.fn();
// const mockAxios = axios as jest.Mocked<typeof axios>;
// jest.mock('axios');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
jest.mock('react-toastify', () => ({
toast: {
success: jest.fn(),
error: jest.fn(),
},
}));
const toastSuccessSpy = jest.spyOn(toast, 'success');
const toastErrorSpy = jest.spyOn(toast, 'error');
// I will ignore the google login button as I do not know how to test it yet!
jest.mock('../../GoogleButton.tsx', () => {
return () => <div data-testid='mock-google-button' />;
});
beforeEach(() => {
const mockIntersectionObserver = jest.fn();
mockIntersectionObserver.mockReturnValue({
observe: () => null,
unobserve: () => null,
disconnect: () => null,
});
window.IntersectionObserver = mockIntersectionObserver;
});
describe('should have initial conditions', () => {
it('should have correct heading, input and button', () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
render(<AddItemCard />);
const addItemHeading = screen.getByTestId('add-item-heading');
expect(addItemHeading).toHaveTextContent('Add an Item');
const itemName = screen.getByTestId('item-name');
expect(itemName).toBeInTheDocument();
const quantity = screen.getByTestId('quantity');
expect(quantity).toBeInTheDocument();
const dropdownSelect = screen.queryAllByTestId('dropdown-select');
const categoryDropdown = dropdownSelect[0];
expect(categoryDropdown).toHaveTextContent('Category');
const compartmentDropdown = dropdownSelect[1];
expect(compartmentDropdown).toHaveTextContent('Compartment');
const purchaseDate = screen.getByTestId('purchase-date');
const expiryDate = screen.getByTestId('expiry-date');
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
expect(purchaseDate).toHaveValue(formattedDate);
expect(expiryDate).toHaveValue(formattedDate);
const addItemButton = screen.getByTestId('add-item-button');
expect(addItemButton).toBeInTheDocument();
errorSpy.mockRestore();
});
});
describe('add item card functionality', () => {
it('should throw error if any feilds empty', async () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
render(<AddItemCard />);
const user = userEvent.setup();
const itemName = screen.getByTestId('item-name');
await user.clear(itemName);
const quantity = screen.getByTestId('quantity');
await user.clear(quantity);
const addItemButton = screen.getByTestId('add-item-button');
await user.click(addItemButton);
await waitFor(() =>
expect(toastErrorSpy).toHaveBeenCalledWith(
'All fields have to be filled.'
)
);
errorSpy.mockRestore();
});
it('should throw error if any feilds empty', async () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
render(<AddItemCard />);
const user = userEvent.setup();
const itemName = screen.getByTestId('item-name');
await user.clear(itemName);
const quantity = screen.getByTestId('quantity');
await user.clear(quantity);
const addItemButton = screen.getByTestId('add-item-button');
await user.click(addItemButton);
await waitFor(() =>
expect(toastErrorSpy).toHaveBeenCalledWith(
'All fields have to be filled.'
)
);
errorSpy.mockRestore();
});
it('should show purchase and expiry date title when no on hover', async () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
render(<AddItemCard />);
const user = userEvent.setup();
const purchaseTitle = screen.getByTestId('purchase-date-title');
expect(purchaseTitle).toBeInTheDocument();
const purchaseTitleStyle = window.getComputedStyle(purchaseTitle);
expect(purchaseTitleStyle.visibility).toBe('visible');
const expiryTitle = screen.getByTestId('expiry-date-title');
expect(expiryTitle).toBeInTheDocument();
const expiryTitleStyle = window.getComputedStyle(expiryTitle);
expect(expiryTitleStyle.visibility).toBe('visible');
errorSpy.mockRestore();
});
// apparently we cannot persist a hover state in react testing library thus this test will fail
// it('should not show purchase title when hovered', () => {
// render(<AddItemCard />);
// const purchaseTitle = screen.getByTestId('purchase-date-title');
// expect(purchaseTitle).toBeInTheDocument();
// fireEvent.mouseOver(purchaseTitle);
// expect(purchaseTitle).toHaveStyle('visibility: hidden');
// fireEvent.mouseOut(purchaseTitle);
// expect(purchaseTitle).not.toHaveStyle('visibility: hidden');
// });
});
|
import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import { List } from './List';
import { Button } from '../Button/Button';
import { ListProps } from './List.types';
export default {
title: 'Atoms/List',
component: List,
} as ComponentMeta<typeof List>;
const Template: ComponentStory<typeof List> = (args: ListProps) => (
<List {...args} />
);
export const Ordered = Template.bind({});
Ordered.args = {
ordered: true,
items: [
<Button variant='secondary' label='BTN 1' />,
<Button variant='secondary' label='BTN 2' />,
<Button label='BTN 3' />,
],
};
export const Unordered = Template.bind({});
Unordered.args = {
items: [
<Button variant='secondary' label='BTN 1' />,
<Button variant='secondary' label='BTN 2' />,
<Button label='BTN 3' />,
],
};
|
<template >
<q-page class="flex flex-center">
<q-card class="budget-card flex q-ma-md q-pa-lg">
<q-card-section class="budget col">
<div class="text-h4 q-mb-lg">Budget</div>
<div class="text-h5 q-mb-sm q-mt-md">Destination</div>
<q-select outlined v-model="destination" :options="options" dense />
<div class="text-h5 q-mb-sm q-mt-md">Savings per day</div>
<p class="q-mb-sm">How much can you afford to save every day?</p>
<div class="daily-budget flex column">
<q-radio v-model="budgetRadio" :val="5" label="A latte is not a lot, eh ($5)" />
<q-radio v-model="budgetRadio" :val="10" label="Let's talk about tacos ($10)" />
<q-radio v-model="budgetRadio" :val="20" label="Pizza please, duh! ($20)" />
<div class="flex">
<q-radio v-model="budgetRadio" val="custom" label="Custom" />
<div v-if="budgetRadio === 'custom'">
<q-input outlined dense v-model.number="budgetInput" type="number" prefix="$" class="q-ml-sm"/>
</div>
</div>
</div>
<div class="text-h5 q-mb-sm q-mt-md">Length of stay</div>
<q-input outlined dense type="number" v-model.number="days" />
<div class="text-h5 q-mb-sm q-mt-md">Number of people</div>
<q-input outlined dense type="number" v-model.number="people" />
</q-card-section>
<q-card-section class="savings col">
<div class="text-h4 q-mb-lg">Savings Plan</div>
<div class="text-h5 q-mb-sm q-mt-md"></div>
<div class="text-h6"></div>
<div class="projections">
<Projection color="#6aa6e2" :budget="budget" :total="total"/>
<Projection color="#e2a66a" :budget="budget" :increase="20" :total="total"/>
<Projection color="#2ad62a" :budget="budget" :increase="50" :total="total"/>
</div>
<div class="totals q-mt-lg">
<TableBudget @update-total="onUpdateTotal" :destination="destination" :days="days" :people="people" />
</div>
</q-card-section>
</q-card>
</q-page>
</template>
<script>
import Projection from "../components/Projection";
import TableBudget from "../components/TableBudget";
export default {
name: 'PageIndex',
components: {
Projection,
TableBudget,
},
data () {
return {
budgetRadio: 10,
budgetInput: 15,
days: 7,
people: 2,
total: 0,
destination: 'France',
options: ['Mexico', 'France']
}
},
computed: {
budget() {
return this.budgetRadio === 'custom' ? this.budgetInput : this.budgetRadio
}
},
methods: {
onUpdateTotal: function (total) {
this.total = total
},
}
}
</script>
<style lang="scss">
.budget-card {
width: 750px;
}
</style>
|
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AccountService } from '../account.service';
import { ActivatedRoute, Router } from '@angular/router';
import { CustomErrorStateMatcher } from 'src/app/core/form-validators/CustomErrorStateMatcher ';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', Validators.required)
});
returnUrl: string;
matcher = new CustomErrorStateMatcher();
constructor(private accountService: AccountService, private router: Router,
private activatedRoute: ActivatedRoute){
this.returnUrl = this.activatedRoute.snapshot.queryParams['returnUrl'] || '/';
}
onSubmit() {
if(!this.loginForm.invalid) {
this.accountService.login(this.loginForm.value).subscribe({
next: () => this.router.navigateByUrl(this.returnUrl)
})
}
}
}
|
//
// CommonGameNetworkClient.m
// Draw
//
// Created by on 12-7-27.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "CommonGameNetworkClient.h"
#import "GameMessage.pb.h"
#import "LogUtil.h"
#import "GameConstants.h"
#import "StringUtil.h"
#import "ShareGameServiceProtocol.h"
@implementation CommonGameNetworkClient
static CommonGameNetworkClient* _defaultGameNetworkClient;
#pragma LifeCycle Management
- (void)dealloc
{
[super dealloc];
}
+ (CommonGameNetworkClient*)defaultInstance
{
if (_defaultGameNetworkClient != nil)
return _defaultGameNetworkClient;
_defaultGameNetworkClient = [[CommonGameNetworkClient alloc] init];
return _defaultGameNetworkClient;
}
- (void)start:(NSString*)serverAddress port:(int)port
{
[self connect:serverAddress port:port autoReconnect:NO];
}
#pragma mark - Data Handler
- (void)handleData:(NSData*)data
{
@try
{
GameMessage *message = [GameMessage parseFromData:data];
PPDebug(@"RECV MESSAGE, COMMAND = %d, RESULT = %d", [message command], [message resultCode]);
if ([self.delegate respondsToSelector:@selector(handleData:)]){
[self.delegate performSelector:@selector(handleData:) withObject:message];
}
}
@catch(NSException* ex)
{
NSLog(@"catch exception while handleData, exception = %@", [ex debugDescription]);
}
}
#pragma mark - Message ID Methods
- (int)generateMessageId
{
_messageIdIndex ++;
return _messageIdIndex;
}
#pragma mark - Build Message With MAC
- (GameMessage*)build:(GameMessageBuilder*)builder
{
[builder setTimeStamp:time(0)];
NSString* strForEncode = [NSString stringWithFormat:@"%d%d",
[builder messageId], [builder timeStamp]];
[builder setMac:[strForEncode encodeMD5Base64:PROTOCOL_BUFFER_SHARE_KEY]];
// PPDebug(@"[TEST] PB MAC=%@", [builder mac]);
return [builder build];
}
#pragma mark - Send Message
- (void)sendSimpleMessage:(int)command
userId:(NSString*)userId
sessionId:(long)sessionId
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:command];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:userId];
[messageBuilder setSessionId:sessionId];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendGetRoomsRequest:(NSString*)userId
{
[self sendSimpleMessage:GameCommandTypeGetRoomsRequest userId:userId sessionId:0];
}
- (void)sendRegisterRoomsNotificationRequest:(NSArray*)sessionList
userId:(NSString*)userId
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeRegisterRoomsNotificationRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:userId];
RegisterRoomsNotificationRequestBuilder* requestBuilder = [[[RegisterRoomsNotificationRequestBuilder alloc] init] autorelease];
for (PBGameSession* session in sessionList) {
[requestBuilder addSessionIds:session.sessionId];
}
[messageBuilder setRegisterRoomsNotificationRequest:[requestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendUnRegisterRoomsNotificationRequest:(NSArray*)sessionList
userId:(NSString*)userId
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeUnregisterRoomsNotificationRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:userId];
UnRegisterRoomsNotificationRequestBuilder* requestBuilder = [[[UnRegisterRoomsNotificationRequestBuilder alloc] init] autorelease];
for (PBGameSession* session in sessionList) {
[requestBuilder addSessionIds:session.sessionId];
}
[messageBuilder setUnRegisterRoomsNotificationRequest:[requestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendChatMessageRequest:(NSString *)content
contentVoiceId:(NSString *)contentVoiceId
expressionId:(NSString *)expressionId
sessionId:(int)sessionId
userId:(NSString *)userId
{
GameChatRequestBuilder *builder = [[[GameChatRequestBuilder alloc] init] autorelease];
if (content != nil && expressionId == nil) {
[builder setContent:content];
[builder setContentVoiceId:contentVoiceId];
[builder setContentType:1];
}
if (content == nil && expressionId != nil) {
[builder setExpressionId:expressionId];
[builder setContentType:2];
}
GameChatRequest *chatRequest = [builder build];
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeChatRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:userId];
[messageBuilder setSessionId:sessionId];
[messageBuilder setChatRequest:chatRequest];
GameMessage *gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendGetRoomsRequest:(NSString*)userId
startIndex:(int)index
count:(int)count
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeGetRoomsRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:userId];
[messageBuilder setSessionId:0];
[messageBuilder setStartOffset:index];
[messageBuilder setMaxCount:count];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendGetRoomsRequest:(NSString*)userId
startIndex:(int)index
count:(int)count
roomType:(int)type
keyword:(NSString*)keyword
gameId:(NSString*)gameId
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeGetRoomsRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:userId];
[messageBuilder setSessionId:0];
[messageBuilder setStartOffset:index];
[messageBuilder setMaxCount:count];
GetRoomsRequestBuilder *getRoomsRequestBuilder = [[[GetRoomsRequestBuilder alloc] init] autorelease];
[getRoomsRequestBuilder setGameId:gameId];
[getRoomsRequestBuilder setRoomType:type];
[getRoomsRequestBuilder setKeyword:keyword];
[messageBuilder setGetRoomsRequest:[getRoomsRequestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendCreateRoomRequest:(PBGameUser*)user
name:(NSString*)roomName
gameId:(NSString*)gameId
password:(NSString *)password
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeCreateRoomRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:user.userId];
CreateRoomRequestBuilder* requestBuilder =[[[CreateRoomRequestBuilder alloc] init] autorelease];
[requestBuilder setUser:user];
[requestBuilder setRoomName:roomName];
[requestBuilder setGameId:gameId];
[requestBuilder setPassword:password];
CreateRoomRequest* request = [requestBuilder build];
[messageBuilder setCreateRoomRequest:request];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendCreateRoomRequest:(PBGameUser*)user
name:(NSString*)roomName
gameId:(NSString*)gameId
password:(NSString *)password
ruleType:(int)ruleType
{
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeCreateRoomRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setUserId:user.userId];
CreateRoomRequestBuilder* requestBuilder =[[[CreateRoomRequestBuilder alloc] init] autorelease];
[requestBuilder setUser:user];
[requestBuilder setRoomName:roomName];
[requestBuilder setGameId:gameId];
[requestBuilder setPassword:password];
[requestBuilder setRuleType:ruleType];
CreateRoomRequest* request = [requestBuilder build];
[messageBuilder setCreateRoomRequest:request];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendJoinGameRequest:(PBGameUser*)user gameId:(NSString*)gameId
{
if (user == nil || gameId == nil)
return;
NSString* userId = [user userId];
JoinGameRequestBuilder *requestBuilder = [[[JoinGameRequestBuilder alloc] init] autorelease];
[requestBuilder setUserId:userId];
[requestBuilder setGameId:gameId];
[requestBuilder setNickName:[user nickName]];
[requestBuilder setUser:user];
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeJoinGameRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setJoinGameRequest:[requestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendJoinGameRequest:(PBGameUser*)user
gameId:(NSString*)gameId
ruleType:(int)ruleType
{
if (user == nil || gameId == nil)
return;
NSString* userId = [user userId];
JoinGameRequestBuilder *requestBuilder = [[[JoinGameRequestBuilder alloc] init] autorelease];
[requestBuilder setUserId:userId];
[requestBuilder setGameId:gameId];
[requestBuilder setNickName:[user nickName]];
[requestBuilder setUser:user];
[requestBuilder setRuleType:ruleType];
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeJoinGameRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setJoinGameRequest:[requestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendJoinGameRequest:(PBGameUser*)user
gameId:(NSString*)gameId
sessionId:(long)sessionId
{
if (user == nil || gameId == nil)
return;
NSString* userId = [user userId];
JoinGameRequestBuilder *requestBuilder = [[[JoinGameRequestBuilder alloc] init] autorelease];
[requestBuilder setUserId:userId];
[requestBuilder setGameId:gameId];
[requestBuilder setNickName:[user nickName]];
[requestBuilder setUser:user];
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeJoinGameRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setSessionId:sessionId];
[messageBuilder setJoinGameRequest:[requestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendJoinGameRequest:(PBGameUser*)user
gameId:(NSString*)gameId
sessionId:(long)sessionId
ruleType:(int)ruleType
{
if (user == nil || gameId == nil)
return;
NSString* userId = [user userId];
JoinGameRequestBuilder *requestBuilder = [[[JoinGameRequestBuilder alloc] init] autorelease];
[requestBuilder setUserId:userId];
[requestBuilder setGameId:gameId];
[requestBuilder setNickName:[user nickName]];
[requestBuilder setUser:user];
[requestBuilder setRuleType:ruleType];
GameMessageBuilder *messageBuilder = [[[GameMessageBuilder alloc] init] autorelease];
[messageBuilder setCommand:GameCommandTypeJoinGameRequest];
[messageBuilder setMessageId:[self generateMessageId]];
[messageBuilder setSessionId:sessionId];
[messageBuilder setJoinGameRequest:[requestBuilder build]];
GameMessage* gameMessage = [self build:messageBuilder];
[self sendData:[gameMessage data]];
}
- (void)sendQuitGameRequest:(NSString*)userId
sessionId:(int)sessionId
{
[self sendSimpleMessage:GameCommandTypeQuitGameRequest userId:userId sessionId:sessionId];
}
@end
|
package com.revature.P0.dl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.revature.P0.models.Order;
import com.revature.P0.models.Product;
import com.revature.P0.util.ConnectionFactory;
public class OrderDBDAO implements DAO<Order>{
DAO<Product> productDAO = new ProductDBDAO();
@Override
public void addInstance(Order newInstance) {
// TODO Auto-generated method stub
try(Connection conn = ConnectionFactory.getInstance().getConnection()){
String query = "Insert into orders (order_id, customer_name, store_name,total_cost,storeId) values (?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, newInstance.orderNumber);
pstmt.setString(2, newInstance.customerName);
pstmt.setString(3,newInstance.storeName);
pstmt.setDouble(4, newInstance.totalCost);
pstmt.setInt(5, newInstance.storeId);
pstmt.execute();
for(Product item : newInstance.items) {
String query2 = "Insert into line_items (order_id,product_id,quantity) values (?,?,?)";
PreparedStatement pstmt2 = conn.prepareStatement(query2);
pstmt2.setInt(1, newInstance.orderNumber);
pstmt2.setInt(2, item.getProductId());
pstmt2.setInt(3, 1);
pstmt2.execute();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public ArrayList<Order> getAllInstances() {
// TODO Auto-generated method stub
try(Connection conn = ConnectionFactory.getInstance().getConnection()){
ArrayList<Order> orders = new ArrayList<Order>();
String query = "select * from line_items li \n"
+ "inner join products p on p.productId = li.product_id\n"
+ "inner join orders o on o.order_id = li.order_id";
PreparedStatement pstmt = conn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
Boolean duplicate = false;
Order order = new Order();
order.orderNumber = rs.getInt("order_id");
order.storeName =rs.getString("store_name");
order.customerName = rs.getString("customer_name");
order.totalCost = rs.getDouble("total_cost");
order.storeId = rs.getInt("storeid");
order.items.addAll(((ProductDBDAO) productDAO).getAllByOrderId(order.orderNumber));
for(Order ord : orders) {
if(order.orderNumber == ord.orderNumber) {
duplicate = true;
}
}
if(duplicate == false) {
orders.add(order);
} else {
continue;
}
}
return orders;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public Order getByName(String Name) {
try(Connection conn = ConnectionFactory.getInstance().getConnection()){
String query = "select * from line_items li \n"
+ "inner join products p on p.productId = li.product_id\n"
+ "inner join orders o on o.order_id = li.order_id where customer_name =?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, Name);
ResultSet rs = pstmt.executeQuery();
Order order = new Order();
while(rs.next()) {
order.orderNumber = rs.getInt("order_id");
order.storeName =rs.getString("store_name");
order.customerName = rs.getString("customer_name");
order.totalCost = rs.getDouble("total_cost");
order.storeId = rs.getInt("storeid");
order.items.add(new Product(rs.getString("product_name"),rs.getDouble("price"),rs.getInt("quantity"),rs.getInt("storeId"),rs.getInt("productId")));
}
System.out.println(order);
return order;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ArrayList<Order> getAllByName(String Name){
try(Connection conn = ConnectionFactory.getInstance().getConnection()){
ArrayList<Order> orders = new ArrayList<Order>();
String query = "select * from line_items li \n"
+ "inner join products p on p.productId = li.product_id\n"
+ "inner join orders o on o.order_id = li.order_id where customer_name =?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, Name);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
Boolean duplicate = false;
Order order = new Order();
order.orderNumber = rs.getInt("order_id");
order.storeName =rs.getString("store_name");
order.customerName = rs.getString("customer_name");
order.totalCost = rs.getDouble("total_cost");
order.storeId = rs.getInt("storeid");
order.items.addAll(((ProductDBDAO) productDAO).getAllByOrderId(order.orderNumber));
for(Order ord : orders) {
if(order.orderNumber == ord.orderNumber) {
duplicate = true;
}
}
if(duplicate == false) {
orders.add(order);
} else {
continue;
}
}
return orders;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ArrayList<Order> getAllByStore(String Name){
try(Connection conn = ConnectionFactory.getInstance().getConnection()){
ArrayList<Order> orders = new ArrayList<Order>();
String query = "select * from line_items li \n"
+ "inner join products p on p.productId = li.product_id\n"
+ "inner join orders o on o.order_id = li.order_id where store_name =?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, Name);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
Boolean duplicate = false;
Order order = new Order();
order.orderNumber = rs.getInt("order_id");
order.storeName =rs.getString("store_name");
order.customerName = rs.getString("customer_name");
order.totalCost = rs.getDouble("total_cost");
order.storeId = rs.getInt("storeid");
order.items.addAll(((ProductDBDAO) productDAO).getAllByOrderId(order.orderNumber));
for(Order ord : orders) {
if(order.orderNumber == ord.orderNumber) {
duplicate = true;
}
}
if(duplicate == false) {
orders.add(order);
} else {
continue;
}
}
return orders;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void updateInstance(Order updatedInstance) {
// TODO Auto-generated method stub
}
}
|
{% extends "base.html" %}
{% block content %}
{% load static %}
{% load i18n %}
{% load widget_tweaks %}
<link href="https://unpkg.com/@yaireo/tagify/dist/tagify.css" rel="stylesheet" type="text/css" />
<!-- ===== Start of Login - Register Section ===== -->
<section class="ptb150" id="login">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3 col-xs-12">
<!-- Start of Login Box -->
<div class="login-box">
<div class="login-title">
<h4> {% if current_employer %}You already have employer account {% else %}{% trans 'Register as Employer' %}{% endif %}</h4>
</div>
{% if current_employer %}
<h6 class="ptb50 text-center" >Go to your employer account <a href="{% url 'my_employer_details' %}">{{current_employer.company}}</a></h6>
{% else %}
<form method="post" id="cmform" action="" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
<div class="form-floating mb-3">
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{{ field.label_tag }}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
<div class="text-center">
<button type="submit" class="btn btn-primary">{% trans 'Submit' %}</button>
<a href="{% url 'my_candidate_details' %}" class="btn btn-secondary">{% trans 'Cancel' %}</a>
</div>
</form>
{% endif %}
</div>
</div>
</div>
</div>
</section>
<script src="https://unpkg.com/@yaireo/tagify"></script>
<script src="https://unpkg.com/@yaireo/tagify@3.1.0/dist/tagify.polyfills.min.js"></script>
{% endblock content %}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading; // DispatcherTimer
namespace MainProject._07_Canvas
{
[PetzoldExampleProject(chapterNumber: 7, page: 146)]
public class PlayJeuDeTacquin : Window
{
const int NumberRows = 4;
const int NumberCols = 4;
UniformGrid unigrid;
int xEmpty, yEmpty, iCounter;
Key[] keys = { Key.Left, Key.Right, Key.Up, Key.Down };
Random rand;
UIElement elEmptySpare = new Empty();
[STAThread]
static void Main(string[] args)
{
Application app = new Application();
app.Run(new PlayJeuDeTacquin());
}
// WARNING!!!! перепутано направление перемещение пустого тайла
// клавишами
public PlayJeuDeTacquin()
{
Title = "Jeu de Tacquin";
SizeToContent = SizeToContent.WidthAndHeight;
ResizeMode = ResizeMode.CanMinimize;
Background = SystemColors.ControlBrush;
// Создание объекта StackPanel как содержимого окна
StackPanel stack = new StackPanel();
Content = stack;
// Создание кнопки в верхней части окна
Button btn = new Button();
btn.Content = "_Scramble";
btn.Margin = new Thickness(10);
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.Click += ScrambleOnClick;
stack.Children.Add(btn);
// Создание декоративного объекта Border
Border bord = new Border();
bord.BorderBrush = SystemColors.ControlDarkDarkBrush;
bord.BorderThickness = new Thickness(1);
stack.Children.Add(bord);
// Создание UniformGrid как дочернего объекта Border
unigrid = new UniformGrid();
unigrid.Rows = NumberRows;
unigrid.Columns = NumberCols;
bord.Child = unigrid;
// Создание объектов Tile для заполнения
// всех ячеек, кроме одной
for (int i = 0; i < NumberRows * NumberCols - 1; i++)
{
Tile tile = new Tile();
tile.Text = (i + 1).ToString();
tile.MouseLeftButtonDown += TileOnMouseLeftButtonDown;
unigrid.Children.Add(tile);
}
// создание объекта Empty для заполнения последней ячейки
unigrid.Children.Add(new Empty());
xEmpty = NumberCols - 1;
yEmpty = NumberRows - 1;
}
void TileOnMouseLeftButtonDown(object sender, MouseButtonEventArgs args)
{
Tile tile = sender as Tile;
int iMove = unigrid.Children.IndexOf(tile);
int xMove = iMove % NumberCols;
int yMove = iMove / NumberCols;
if(xMove == xEmpty)
{
while (yMove != yEmpty)
{
MoveTile(xMove, yEmpty + (yMove - yEmpty) / Math.Abs(yMove - yEmpty));
}
}
if(yMove == yEmpty)
{
while(xMove != xEmpty)
{
MoveTile(xEmpty + (xMove - xEmpty) / Math.Abs(xMove - xEmpty), yMove);
}
}
}
protected override void OnKeyDown(KeyEventArgs args)
{
base.OnKeyDown(args);
switch (args.Key)
{
case Key.Right:
{
MoveTile(xEmpty - 1, yEmpty);
break;
}
case Key.Left:
{
MoveTile(xEmpty + 1, yEmpty);
break;
}
case Key.Down:
{
MoveTile(xEmpty, yEmpty - 1);
break;
}
case Key.Up:
{
MoveTile(xEmpty, yEmpty + 1);
break;
}
}
}
void ScrambleOnClick(object sender, RoutedEventArgs args)
{
rand = new Random();
iCounter = 16 * NumberCols * NumberRows;
DispatcherTimer tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromMilliseconds(10);
tmr.Tick += TimerOnTick;
tmr.Start();
}
void TimerOnTick(object sender, EventArgs args)
{
for(int i = 0; i < 5; i++)
{
MoveTile(xEmpty, yEmpty + rand.Next(3) - 1);
MoveTile(xEmpty + rand.Next(3) - 1, yEmpty);
}
if(0 == iCounter--)
{
(sender as DispatcherTimer).Stop();
}
}
void MoveTile (int xTile, int yTile)
{
if((xTile == xEmpty && yTile == yEmpty) ||
xTile < 0 || xTile >= NumberCols ||
yTile < 0 || yTile >= NumberRows)
{
return;
}
int iTile = NumberCols * yTile + xTile;
int iEmpty = NumberCols * yEmpty + xEmpty;
UIElement elTile = unigrid.Children[iTile];
UIElement elEmpty = unigrid.Children[iEmpty];
unigrid.Children.RemoveAt(iTile);
unigrid.Children.Insert(iTile, elEmptySpare);
unigrid.Children.RemoveAt(iEmpty);
unigrid.Children.Insert(iEmpty, elTile);
xEmpty = xTile;
yEmpty = yTile;
elEmptySpare = elEmpty;
}
}
}
|
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next = nullptr;
Node(int data)
{
this->data = data;
this->next = nullptr;
}
};
class LinkedList
{
public:
Node *head = nullptr;
Node *temp, *newNode;
void create(int A[], int size)
{
head = new Node(A[0]);
temp = head;
for (int i = 1; i < size; i++)
{
newNode = new Node(A[i]);
temp->next = newNode;
temp = newNode;
}
}
void display()
{
int count = 0;
Node *p = head;
while (p != nullptr)
{
count++;
cout << p->data << " ";
p = p->next;
}
cout << endl;
cout << "Total Nodes are: " << count << endl;
}
~LinkedList()
{
Node *current = head;
while (current != NULL)
{
Node *next = current->next;
delete current;
current = next;
}
}
};
int main()
{
int A[] = {1, 2, 3, 4, 5};
LinkedList list;
list.create(A, 5);
list.display();
}
|
import React, { useState, useEffect } from 'react';
import data from './data';
import Article from './Article';
const getStorageTheme = () => {
let theme = 'light-theme';
if (localStorage.getItem('theme')) theme = localStorage.getItem('theme');
return theme;
};
function App() {
const [theme, setTheme] = useState(getStorageTheme());
const toggleTheme = () => setTheme(theme === 'light-theme' ? 'dark-theme' : 'light-theme');
useEffect(() => {
document.documentElement.className = theme;
localStorage.setItem('theme', theme);
}, [theme]);
return (
<main>
<nav>
<div className="nav-center">
<h1>overreacted</h1>
<button className="btn" onClick={toggleTheme}>toggle</button>
</div>
</nav>
<section className="articles">
{data.map(item => <Article key={item.id} {...item} />)}
</section>
</main>
);
}
export default App;
|
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// MIT
pragma solidity ^0.8.0;
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// MIT
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}// MIT
pragma solidity ^0.8.0;
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}// MIT
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}// MIT
pragma solidity ^0.8.0;
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}// UNLICENSED
pragma solidity ^0.8.6;
interface IVault {
function vidyaRate() external view returns (uint256);
function totalPriority() external view returns (uint256);
function tellerPriority(address tellerId) external view returns (uint256);
function addTeller(address teller, uint256 priority) external;
function changePriority(address teller, uint256 newPriority) external;
function payProvider(
address provider,
uint256 providerTimeWeight,
uint256 totalWeight
) external;
function calculateRateExternal() external;
}// UNLICENSED
pragma solidity ^0.8.6;
contract Teller is Ownable, ReentrancyGuard {
using Address for address;
using SafeERC20 for IERC20;
event TellerDeployed();
event TellerToggled(address teller, bool status);
event NewCommitmentAdded(
uint256 bonus,
uint256 time,
uint256 penalty,
uint256 deciAdjustment
);
event CommitmentToggled(uint256 index, bool status);
event PurposeSet(address devAddress, bool purposeStatus);
event LpDeposited(address indexed provider, uint256 indexed amount);
event Withdrew(address indexed provider, uint256 indexed amount);
event Commited(address indexed provider, uint256 indexed commitedAmount);
event CommitmentBroke(address indexed provider, uint256 indexed tokenSentAmount);
event Claimed(address indexed provider, bool indexed success);
struct Provider {
uint256 LPDepositedRatio;
uint256 userWeight;
uint256 lastClaimedTime;
uint256 commitmentIndex;
uint256 committedAmount;
uint256 commitmentEndTime;
}
struct Commitment {
uint256 bonus;
uint256 duration;
uint256 penalty;
uint256 deciAdjustment;
bool isActive;
}
IVault public Vault;
IERC20 public LpToken;
uint256 public totalLP;
uint256 public totalWeight;
uint256 public tellerClosedTime;
bool public tellerOpen;
bool public purpose;
address public devAddress;
Commitment[] public commitmentInfo;
mapping(address => Provider) public providerInfo;
modifier isTellerOpen() {
require(tellerOpen, "Teller: Teller is not open.");
_;
}
modifier isProvider() {
require(
providerInfo[msg.sender].LPDepositedRatio != 0,
"Teller: Caller is not a provider."
);
_;
}
modifier isTellerClosed() {
require(!tellerOpen, "Teller: Teller is still active.");
_;
}
constructor(IERC20 _LpToken, IVault _Vault) {
LpToken = _LpToken;
Vault = _Vault;
commitmentInfo.push();
emit TellerDeployed();
}
function toggleTeller() external onlyOwner {
tellerOpen = !tellerOpen;
tellerClosedTime = block.timestamp;
emit TellerToggled(address(this), tellerOpen);
}
function addCommitment(
uint256 _bonus,
uint256 _days,
uint256 _penalty,
uint256 _deciAdjustment
) external onlyOwner {
Commitment memory holder;
holder.bonus = _bonus;
holder.duration = _days * 1 days;
holder.penalty = _penalty;
holder.deciAdjustment = _deciAdjustment;
holder.isActive = true;
commitmentInfo.push(holder);
emit NewCommitmentAdded(_bonus, _days, _penalty, _deciAdjustment);
}
function toggleCommitment(uint256 _index) external onlyOwner {
require(
0 < _index && _index < commitmentInfo.length,
"Teller: Current index is not listed in the commitment array."
);
commitmentInfo[_index].isActive = !commitmentInfo[_index].isActive;
emit CommitmentToggled(_index, commitmentInfo[_index].isActive);
}
function setPurpose(address _address, bool _status) external onlyOwner {
purpose = _status;
devAddress = _address;
emit PurposeSet(devAddress, purpose);
}
function depositLP(uint256 _amount) external isTellerOpen {
uint256 contractBalance = LpToken.balanceOf(address(this));
LpToken.safeTransferFrom(msg.sender, address(this), _amount);
Provider storage user = providerInfo[msg.sender];
if (user.LPDepositedRatio != 0) {
commitmentFinished();
claim();
} else {
user.lastClaimedTime = block.timestamp;
}
if (contractBalance == totalLP || totalLP == 0) {
user.LPDepositedRatio += _amount;
totalLP += _amount;
} else {
uint256 _adjustedAmount = (_amount * totalLP) / contractBalance;
user.LPDepositedRatio += _adjustedAmount;
totalLP += _adjustedAmount;
}
user.userWeight += _amount;
totalWeight += _amount;
emit LpDeposited(msg.sender, _amount);
}
function withdraw(uint256 _amount) external isProvider nonReentrant {
Provider storage user = providerInfo[msg.sender];
uint256 contractBalance = LpToken.balanceOf(address(this));
commitmentFinished();
uint256 userTokens = (user.LPDepositedRatio * contractBalance) /
totalLP;
require(
userTokens - user.committedAmount >= _amount,
"Teller: Provider hasn't got enough deposited LP tokens to withdraw."
);
claim();
uint256 _weightChange = (_amount * user.userWeight) / userTokens;
user.userWeight -= _weightChange;
totalWeight -= _weightChange;
uint256 ratioChange = _amount * totalLP/contractBalance;
user.LPDepositedRatio -= ratioChange;
totalLP -= ratioChange;
LpToken.safeTransfer(msg.sender, _amount);
emit Withdrew(msg.sender, _amount);
}
function tellerClosedWithdraw() external isTellerClosed isProvider {
uint256 contractBalance = LpToken.balanceOf(address(this));
require(contractBalance != 0, "Teller: Contract balance is zero.");
claim();
Provider memory user = providerInfo[msg.sender];
uint256 userTokens = (user.LPDepositedRatio * contractBalance) /
totalLP;
totalLP -= user.LPDepositedRatio;
totalWeight -= user.userWeight;
providerInfo[msg.sender] = Provider(0, 0, 0, 0, 0, 0);
LpToken.safeTransfer(msg.sender, userTokens);
emit Withdrew(msg.sender, userTokens);
}
function commit(uint256 _amount, uint256 _commitmentIndex)
external
nonReentrant
isProvider
{
require(
commitmentInfo[_commitmentIndex].isActive,
"Teller: Current commitment is not active."
);
Provider storage user = providerInfo[msg.sender];
commitmentFinished();
uint256 contractBalance = LpToken.balanceOf(address(this));
uint256 userTokens = (user.LPDepositedRatio * contractBalance) /
totalLP;
require(
userTokens - user.committedAmount >= _amount,
"Teller: Provider hasn't got enough deposited LP tokens to commit."
);
if (user.committedAmount != 0) {
require(
_commitmentIndex == user.commitmentIndex,
"Teller: Commitment index is not the same as providers'."
);
}
uint256 newEndTime;
if (
user.commitmentEndTime >= block.timestamp &&
user.committedAmount != 0
) {
newEndTime = calculateNewEndTime(
user.committedAmount,
_amount,
user.commitmentEndTime,
_commitmentIndex
);
} else {
newEndTime =
block.timestamp +
commitmentInfo[_commitmentIndex].duration;
}
uint256 weightToGain = (_amount * user.userWeight) / userTokens;
uint256 bonusCredit = commitBonus(_commitmentIndex, weightToGain);
claim();
user.commitmentIndex = _commitmentIndex;
user.committedAmount += _amount;
user.commitmentEndTime = newEndTime;
user.userWeight += bonusCredit;
totalWeight += bonusCredit;
emit Commited(msg.sender, _amount);
}
function breakCommitment() external nonReentrant isProvider {
Provider memory user = providerInfo[msg.sender];
require(
user.commitmentEndTime > block.timestamp,
"Teller: No commitment to break."
);
uint256 contractBalance = LpToken.balanceOf(address(this));
uint256 tokenToReceive = (user.LPDepositedRatio * contractBalance) /
totalLP;
Commitment memory currentCommit = commitmentInfo[user.commitmentIndex];
uint256 fee = (user.committedAmount * currentCommit.penalty) /
currentCommit.deciAdjustment;
tokenToReceive -= fee;
totalLP -= user.LPDepositedRatio;
totalWeight -= user.userWeight;
providerInfo[msg.sender] = Provider(0, 0, 0, 0, 0, 0);
if (purpose) {
LpToken.safeTransfer(devAddress, fee / 10);
}
LpToken.safeTransfer(msg.sender, tokenToReceive);
emit CommitmentBroke(msg.sender, tokenToReceive);
}
function claim() internal {
Provider storage user = providerInfo[msg.sender];
uint256 timeGap = block.timestamp - user.lastClaimedTime;
if (!tellerOpen) {
timeGap = tellerClosedTime - user.lastClaimedTime;
}
if (timeGap > 365 * 1 days) {
timeGap = 365 * 1 days;
}
uint256 timeWeight = timeGap * user.userWeight;
user.lastClaimedTime = block.timestamp;
Vault.payProvider(msg.sender, timeWeight, totalWeight);
emit Claimed(msg.sender, true);
}
function commitBonus(uint256 _commitmentIndex, uint256 _amount)
internal
view
returns (uint256)
{
if (commitmentInfo[_commitmentIndex].isActive) {
return
(commitmentInfo[_commitmentIndex].bonus * _amount) /
commitmentInfo[_commitmentIndex].deciAdjustment;
}
return 0;
}
function calculateNewEndTime(
uint256 _oldAmount,
uint256 _extraAmount,
uint256 _oldEndTime,
uint256 _commitmentIndex
) internal view returns (uint256) {
uint256 extraEndTIme = commitmentInfo[_commitmentIndex].duration +
block.timestamp;
uint256 newEndTime = ((_oldAmount * _oldEndTime) +
(_extraAmount * extraEndTIme)) / (_oldAmount + _extraAmount);
return newEndTime;
}
function commitmentFinished() internal {
Provider storage user = providerInfo[msg.sender];
if (user.commitmentEndTime <= block.timestamp) {
user.committedAmount = 0;
user.commitmentIndex = 0;
}
}
function claimExternal() external isTellerOpen isProvider nonReentrant {
commitmentFinished();
claim();
}
function getUserInfo(address _user)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
Provider memory user = providerInfo[_user];
if (user.LPDepositedRatio > 0) {
uint256 claimAmount = (Vault.vidyaRate() *
Vault.tellerPriority(address(this)) *
(block.timestamp - user.lastClaimedTime) *
user.userWeight) / (totalWeight * Vault.totalPriority());
uint256 totalLPDeposited = (providerInfo[msg.sender]
.LPDepositedRatio * LpToken.balanceOf(address(this))) / totalLP;
if (user.commitmentEndTime > block.timestamp) {
return (
user.commitmentEndTime - block.timestamp,
user.committedAmount,
user.commitmentIndex,
claimAmount,
totalLPDeposited
);
} else {
return (0, 0, 0, claimAmount, totalLPDeposited);
}
} else {
return (0, 0, 0, 0, 0);
}
}
}
|
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ApiService } from '../services/api.service';
import { Endereco } from '../models/endereco.model';
import { Imovel } from '../models/imovel.model';
@Component({
selector: 'app-imovel',
templateUrl: './imovel.component.html',
styleUrls: ['./imovel.component.sass']
})
export class ImovelComponent implements OnInit {
imovel!: Imovel;
editarImovel: boolean = false;
imovelForm!: FormGroup;
imoveis: Imovel[] = [];
constructor(private formBuilder: FormBuilder, private apiService: ApiService) {}
ngOnInit(): void {
this.imovelForm = this.formBuilder.group({
id: null,
nome: '',
tipo: '',
valor: null,
cep: '',
rua: '',
cidade: '',
localidade: '',
// outras propriedades necessárias
});
this.apiService.getImoveis().subscribe((imoveis: Imovel[]) => {
this.imoveis = imoveis;
});
}
saveImovel(): void {
this.apiService.createImovel(this.imovelForm.value).subscribe((response) => {
// Lógica após salvar o imóvel
});
}
toggleEditarImovel(): void {
this.editarImovel = !this.editarImovel;
}
updateImovel(): void {
const id = this.imovelForm.value.id;
this.apiService.updateImovel(id, this.imovelForm.value).subscribe((response) => {
// Lógica após atualizar o imóvel
});
}
deleteImovel(imovel: Imovel): void {
this.apiService.deleteImovel(imovel.id).subscribe(() => {
// Lógica adicional, se necessário
});
}
getCep(): void {
const cep = this.imovelForm.value.cep;
this.apiService.getEnderecoByCep(cep).subscribe((endereco: Endereco) => {
this.imovelForm.patchValue({
rua: endereco.logradouro,
cidade: endereco.cidade,
localidade: endereco.localidade,
// atualize outras propriedades do endereço conforme necessário
});
});
}
onSubmit(): void {
if (this.imovelForm.invalid) {
return;
}
// Lógica para manipular o formulário enviado
}
}
|
<!DOCTYPE html>
<html lang="pt-br">
<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/style.css">
<link rel="stylesheet" href="./css/contatos.css">
<!-- Incones -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<!-- Fontes -->
<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=Montserrat:wght@300;400;500;600;700&family=Oswald&display=swap"
rel="stylesheet">
<title>Document</title>
</head>
<body>
<!-- ==========Inicio Navigation========== -->
<nav>
<div class="container nav_container">
<a href="/">
<h4>ESCOLA</h4>
</a>
<ul class="nav_menu">
<li><a href="/">Home</a></li>
<li><a href="/sobre.html">Sobre</a></li>
<li><a href="/cursos.html">Cursos</a></li>
<li><a href="/contatos.html">Contatos</a></li>
</ul>
<button class="open_menu_bt btn"><i class="fa-solid fa-bars"></i></button>
<button class="close_menu_bt btn"><i class="fa-solid fa-xmark"></i></button>
</div>
</nav>
<!-- ==========Fim Navigation========== -->
<!-- ==========Header========== -->
<section class="contatos">
<div class="container contatos-container">
<div class="contatos_esquerdo">
<div class="imagem_contato">
<img src="./imagens/sobre.png" alt="" srcset="">
</div>
<h1>Contatos</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Non praesentium porro inventore vel
distinctio magni, natus animi omnis?</p>
<article class="contato">
<h4>Contatos</h4>
<a href="#">(85)9.1111-0000</a><br>
<a href="#">exemplo@email.com</a>
<ul>
<li>
<a href="https://facebook.com"> <i class="fa-brands fa-facebook"></i></a>
</li>
<li>
<a href="https://instagram.com"><i class="fa-brands fa-instagram"></i></a>
</li>
<li>
<a href="https://linkedin.com"><i class="fa-brands fa-linkedin"></i></a>
</li>
<li>
<a href="https://twitter.com"><i class="fa-brands fa-twitter"></i></a>
</li>
</ul>
</article>
</div>
<div class="contatos_direito">
<form class="form_name" action="https://formspree.io/f/xwkywrgb" method="post">
<input type="text" name="primeiro_nome" placeholder="nome">
<input type="text" name="segundo_nome" placeholder="sobrenome">
<input type="email" name="email" placeholder="email">
<textarea name="" id="" rows="5"></textarea>
<button class="btn btn-primary">Enviar</button>
</form>
</div>
</div>
</div>
<!-- ==========Inicio Footer ========== -->
<footer>
<div class="container footer_container">
<article>
<h4>Escola</h4>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tempore error.</p>
</article>
<article>
<h4>Link Permanentes</h4>
<a href="#">Home</a><br>
<a href="#">Sobre</a><br>
<a href="#">Cursos</a><br>
<a href="#">Contatos</a><br>
</article>
<article>
<h4>Uso</h4>
<h5>Termos</h5>
<h5>Politicas</h5>
</article>
<article class="footer_contatos">
<h4>Contatos</h4>
<a href="#">(85)9.1111-0000</a>
<a href="#">exemplo@email.com</a>
<ul>
<li>
<a href="https://facebook.com"> <i class="fa-brands fa-facebook"></i></a>
</li>
<li>
<a href="https://instagram.com"><i class="fa-brands fa-instagram"></i></a>
</li>
<li>
<a href="https://linkedin.com"><i class="fa-brands fa-linkedin"></i></a>
</li>
<li>
<a href="https://twitter.com"><i class="fa-brands fa-twitter"></i></a>
</li>
</ul>
</article>
</div>
</footer>
<div class="direitos">
<h5>Direitor Autorais ©</h5>
</div>
<script src="./js/main.js"></script>
</body>
</html>
|
// https://golangbyexample.com/interface-in-golang/
package main
import "fmt"
type animal interface {
breathe()
walk()
farts()
}
type human interface {
animal
speak()
}
type employee struct {
name string
}
func (e employee) breathe() {
fmt.Println("Employee breathes")
}
func (e employee) walk() {
fmt.Println("Employee walk")
}
func (e employee) farts() {
fmt.Println("Employee farts")
}
func (e employee) speak() {
fmt.Println("Employee speaks")
}
func main() {
var h human
h = employee{name: "Jozeph"}
h.breathe()
h.walk()
h.farts()
h.speak()
fmt.Println()
fmt.Printf("Type of h is: %T\n", h)
}
|
import { getAuthSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { createErrorResponse } from "@/lib/utils";
import { ProductFormValidator } from "@/lib/validators/productForm";
import { z } from "zod";
export async function POST(req: Request) {
try {
const session = await getAuthSession();
if (!session?.user) {
return new Response("Unauthorized", {
status: 401,
});
}
const body = await req.json();
const { name, image, description, category, brand, price, tags } =
ProductFormValidator.parse(body);
const res = await prisma.product.create({
data: {
name,
image: image || "",
description,
price,
category: { connect: { id: category } },
brand: { connect: { id: brand } },
tags: {
create: tags.map((tag) => ({
tag: { connect: { id: tag } },
})),
},
},
});
const successResponse = JSON.stringify({
success: true,
message: "Product created successfully!",
});
return new Response(successResponse, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (err) {
console.error("Error while sending req: ", err);
if (err instanceof z.ZodError)
return new Response(err.message, {
status: 422,
});
return new Response("Could not create product", { status: 500 });
}
}
export async function GET(req: Request) {
const session = await getAuthSession();
if (!session?.user) {
return createErrorResponse(
"You are Unauthorized. Please login to your account",
401
);
}
const { searchParams } = new URL(req.url);
const id = await searchParams.get("id");
if (id) {
let productRes = await prisma.product.findFirst({
where: {
id,
},
include: {
tags: true,
},
});
const tagIDs = productRes?.tags.map((tag) => tag.tagId) || [];
const tags = await prisma.tag.findMany({
where: {
id: {
in: tagIDs,
},
},
});
const product = {
id: productRes?.id,
name: productRes?.name,
image: productRes?.image,
description: productRes?.description,
price: productRes?.price,
categoryId: productRes?.categoryId,
brandId: productRes?.brandId,
createdAt: productRes?.createdAt,
updatedAt: productRes?.updatedAt,
tagIDs,
tags,
};
const successResponse = JSON.stringify({
success: true,
message: "Product fetched successfully!",
data: product,
});
return new Response(successResponse, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} else {
try {
const products = await prisma.product.findMany();
const successResponse = JSON.stringify({
success: true,
message: "Products fetched successfully!",
data: products,
});
return new Response(successResponse, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (err) {
console.log("Unable to fetch products", err);
return createErrorResponse("Unable to fetch products", 422);
}
}
}
export async function PUT(req: Request) {
const session = await getAuthSession();
if (!session?.user) {
return createErrorResponse(
"You are Unauthorized. Please login to your account",
401
);
}
const { searchParams } = new URL(req.url);
const id = await searchParams.get("id");
if (!id) {
return createErrorResponse(
"Please provide a valid ID in order to update a product",
400
);
}
const body = await req.json();
try {
const { name, image, description, category, brand, price, tags } =
ProductFormValidator.parse(body);
const existingProduct = await prisma.product.findUnique({
where: {
id,
},
});
if (!existingProduct) {
return createErrorResponse("Product not found", 404);
}
const updatedProduct = await prisma.product.update({
where: {
id,
},
data: {
name,
image: image || "",
description,
price,
category: { connect: { id: category } },
brand: { connect: { id: brand } },
tags: {
create: tags.map((tag) => ({
tag: { connect: { id: tag } },
})),
},
},
});
console.log("updatedProduct", updatedProduct);
const successResponse = JSON.stringify({
success: true,
message: "Product updated successfully!",
data: updatedProduct,
});
return new Response(successResponse, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (err) {
if (err instanceof z.ZodError) return createErrorResponse(err.message, 400);
console.log("[server] Error while updating product", err);
return createErrorResponse(
"An error occurred while updating the product",
500
);
}
}
export async function DELETE(req: Request) {
const session = await getAuthSession();
if (!session?.user) {
return createErrorResponse(
"You are Unauthorized. Please login to your account",
401
);
}
const { searchParams } = new URL(req.url);
const id = await searchParams.get("id");
if (!id) {
return createErrorResponse(
"Please provide a valid ID in order to delete a product",
400
);
}
try {
const productByID = await prisma.product.findUnique({
where: {
id,
},
include: {
tags: true,
},
});
if (!productByID) {
return createErrorResponse(
"There is an issue while product deletion.",
404
);
}
await prisma.tagsOnProducts.deleteMany({
where: {
productId: id,
},
});
await prisma.product.delete({
where: {
id,
},
});
const successResponse = JSON.stringify({
success: true,
message: "Product deleted successfully!",
});
return new Response(successResponse, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (err) {
console.log("[server] Error 404", err);
return createErrorResponse(
"An error occurred while attempting to delete the product",
500
);
}
}
|
import json
import os
from unittest.mock import ANY, MagicMock, call
from urllib.parse import quote
import pytest
from bitbucketcli.bitbucket.repository import RepositoryCommand
@pytest.mark.parametrize(
"workspace,name,project_key,is_private,status_code",
[
("workspace1", "repository1", "projectkey1", True, 200),
("workspace2", "repository2", "projectkey2", False, 200),
("workspace3", "repository3", "projectkey3", True, 200),
],
)
def test_create_repository(
mock_session, workspace, name, project_key, is_private, status_code
):
repository_create_url = f"{api_repositories_url()}/{workspace}/{name}"
branch_restriction_url = (
f"{api_repositories_url()}/{workspace}/{name}/branch-restrictions"
)
create_repository_payload = json.dumps(
{
"scm": "git",
"project": {"key": project_key},
"is_private": is_private,
"name": name,
}
)
headers = {"Accept": "application/json", "Content-Type": "application/json"}
create_repository_mock = MagicMock(name="create_repository_mock")
create_repository_mock.status_code = status_code
create_repository_mock.json.return_value = {"mainbranch": {"name": "master"}}
push_restriction_mock = MagicMock(name="push_restriction_mock")
force_restriction_mock = MagicMock(name="force_restriction_mock")
delete_restriction_mock = MagicMock(name="delete_restriction_mock")
push_restriction_payload = json.dumps(restriction_payload("push"))
force_restriction_payload = json.dumps(restriction_payload("force"))
delete_restriction_payload = json.dumps(restriction_payload("delete"))
payloads = [
create_repository_mock,
push_restriction_mock,
force_restriction_mock,
delete_restriction_mock,
]
mock_session.post.side_effect = payloads
repository = RepositoryCommand(workspace, mock_session)
create_result = repository.create(name, project_key, is_private)
assert create_result is True
assert mock_session.post.call_count == 4
mock_session.post.assert_has_calls(
[
call(
url=repository_create_url,
data=create_repository_payload,
headers=headers,
params=None,
),
call(
url=branch_restriction_url,
data=push_restriction_payload,
headers=headers,
params=None,
),
call(
url=branch_restriction_url,
data=force_restriction_payload,
headers=headers,
params=None,
),
call(
url=branch_restriction_url,
data=delete_restriction_payload,
headers=headers,
params=None,
),
]
)
@pytest.mark.parametrize(
"workspace,name,project_key,is_private,status_code",
[
("workspace1", "repository1", "projectkey1", True, 400),
("workspace2", "repository2", "projectkey2", False, 400),
("workspace3", "repository3", "projectkey3", True, 400),
("workspace1", "repository1", "projectkey1", True, 401),
("workspace2", "repository2", "projectkey2", False, 401),
("workspace3", "repository3", "projectkey3", True, 401),
],
)
def test_fail_to_create_repository(
mock_session, workspace, name, project_key, is_private, status_code
):
repository_create_url = f"{api_repositories_url()}/{workspace}/{name}"
create_repository_payload = json.dumps(
{
"scm": "git",
"project": {"key": project_key},
"is_private": is_private,
"name": name,
}
)
create_repository_mock = MagicMock()
create_repository_mock.status_code = status_code
payloads = [
create_repository_mock,
]
mock_session.post.side_effect = payloads
repository = RepositoryCommand(workspace, mock_session)
create_result = repository.create(name, project_key, is_private)
assert create_result is False
mock_session.post.assert_called_with(
url=repository_create_url,
data=create_repository_payload,
headers={"Accept": "application/json", "Content-Type": "application/json"},
params=None,
)
@pytest.mark.parametrize(
"workspace,email,repository_name,permission,status_code",
[
("workspace1", "fancyemail@email.com", "repository1", "admin", 200),
("workspace2", "fancyemail@email.com", "repository2", "write", 200),
("workspace3", "fancyemail@email.com", "repository3", "read", 200),
("workspace1", "fancyemail@email.com", "repository1", "read", 200),
("workspace2", "fancyemail@email.com", "repository2", "write", 200),
("workspace3", "fancyemail@email.com", "repository3", "admin", 200),
],
)
def test_add_user_with_success(
workspace, email, repository_name, permission, status_code
):
url = f"{internal_api_url()}/\u0021api/internal/invitations/repositories/{workspace}/{repository_name}"
session_mock = MagicMock()
session_mock.post.return_value.status_code = status_code
repository = RepositoryCommand(workspace, session_mock)
result = repository.add_user_to_repository(email, repository_name, permission)
payload = {"emails": [email], "permission": permission}
assert result is True
session_mock.post.assert_called_with(
url=url,
data=json.dumps(payload),
headers={"Accept": "application/json", "Content-Type": "application/json"},
params=ANY,
)
@pytest.mark.parametrize(
"workspace,email,repository_name,permission,status_code",
[
("workspace1", "fancyemail@email.com", "repository1", "admin", 400),
("workspace2", "fancyemail@email.com", "repository2", "write", 400),
("workspace3", "fancyemail@email.com", "repository3", "read", 400),
("workspace1", "fancyemail@email.com", "repository1", "read", 400),
("workspace2", "fancyemail@email.com", "repository2", "write", 400),
("workspace3", "fancyemail@email.com", "repository3", "admin", 400),
],
)
def test_fail_to_add_user(workspace, email, repository_name, permission, status_code):
url = f"{internal_api_url()}/\u0021api/internal/invitations/repositories/{workspace}/{repository_name}"
session_mock = MagicMock()
session_mock.post.return_value.status_code = status_code
repository = RepositoryCommand(workspace, session_mock)
result = repository.add_user_to_repository(email, repository_name, permission)
payload = {"emails": [email], "permission": permission}
assert result is False
session_mock.post.assert_called_with(
url=url,
data=json.dumps(payload),
headers={"Accept": "application/json", "Content-Type": "application/json"},
params=ANY,
)
@pytest.mark.parametrize(
"workspace,account_id,repository_name,status_code",
[
(
"workspace1",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository1",
204,
),
(
"workspace2",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository2",
204,
),
(
"workspace3",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository3",
204,
),
(
"workspace1",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository1",
204,
),
(
"workspace2",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository2",
204,
),
(
"workspace3",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository3",
204,
),
],
)
def test_remove_user_with_success(
mocker, workspace, account_id, repository_name, status_code
):
uuid = "{3333333-444444444-444444-44444}"
mocker.patch(
"bitbucketcli.bitbucket.bitbucket.BitbucketClient.get_user_uuid",
return_value=uuid,
)
session_mock = MagicMock()
session_mock.delete.return_value.status_code = status_code
repository = RepositoryCommand(workspace, session_mock)
result = repository.remove_user_from_repository(repository_name, account_id)
url = f"{internal_api_url()}/\u0021api/internal/privileges/{workspace}/{repository_name}/{quote(uuid)}"
assert result is True
assert session_mock.delete.call_count == 1
session_mock.delete.assert_called_with(
url=url, headers={"Accept": "application/json"}, params=None, data=None
)
@pytest.mark.parametrize(
"workspace,account_id,repository_name,status_code",
[
(
"workspace1",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository1",
400,
),
(
"workspace2",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository2",
400,
),
(
"workspace3",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository3",
410,
),
(
"workspace1",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository1",
400,
),
(
"workspace2",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository2",
410,
),
(
"workspace3",
"616030:07848922-j1ee-57f0-acd3-6c7677078h96",
"repository3",
400,
),
],
)
def test_fail_to_remove_user(
mocker, workspace, account_id, repository_name, status_code
):
uuid = "{3333333-444444444-444444-44444}"
mocker.patch(
"bitbucketcli.bitbucket.bitbucket.BitbucketClient.get_user_uuid",
return_value=uuid,
)
session_mock = MagicMock()
session_mock.delete.return_value.status_code = status_code
repository = RepositoryCommand(workspace, session_mock)
result = repository.remove_user_from_repository(repository_name, account_id)
url = f"{internal_api_url()}/\u0021api/internal/privileges/{workspace}/{repository_name}/{quote(uuid)}"
assert result is False
assert session_mock.delete.call_count == 1
session_mock.delete.assert_called_with(
url=url, headers={"Accept": "application/json"}, params=None, data=None
)
def internal_api_url():
return os.getenv("BITBUCKET_INTERNAL_API_URL")
def api_repositories_url():
return f"{os.getenv('BITBUCKET_API_URL')}/2.0/repositories"
def restriction_payload(kind):
return {
"type": "branchrestriction",
"kind": kind,
"branch_match_kind": "glob",
"pattern": "master",
"users": [],
"groups": [],
}
|
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Platform } from '@ionic/angular';
import { Title } from '@angular/platform-browser';
import { IDEAStorageService, IDEATranslationsService } from '@idea-ionic/common';
import { AppService } from './app.service';
import { ConfigurationsService } from './tabs/configurations/configurations.service';
import { ServiceLanguages } from '@models/serviceLanguages.enum';
export const initGuard: CanActivateFn = async (): Promise<boolean> => {
const platform = inject(Platform);
const title = inject(Title);
const storage = inject(IDEAStorageService);
const t = inject(IDEATranslationsService);
const app = inject(AppService);
const _configurations = inject(ConfigurationsService);
if (app.initReady) return true;
await platform.ready();
await storage.ready();
await t.init(Object.values(ServiceLanguages), ServiceLanguages.English);
app.configurations = await _configurations.get();
title.setTitle(app.configurations.appTitle);
app.initReady = true;
return true;
};
|
// Important: Check 'index.html' and check the 'main_canvas' div element
// Necessary for positioning elements within the canvas
// Global Variables
let width = 300, height = 400;
let canvas; // Reference to p5 canvas object (see 'setup()')
// User-Defined Classes
class Input {
constructor(x, y, header="", has_header=true) {
// Attributes
this.elem = null; // Input Box
this.header = null; // Header
this.create_elem(x, y);
if (has_header) { this.create_header(header); }
}
// Methods
create_elem(x, y) {
let input = createInput(); // Creates 'input' element
input.position(x, y); // Positions element
input.parent("main_canvas"); // Requires an HTML element in 'index.html' file
// 'main_canvas' is that element 'id'
this.elem = input; // Assigns
}
create_header(header_str, offset=45, elem_type="h3") {
let header = createElement(elem_type, header_str); // Creates an HTML element
header.position(this.elem.x, this.elem.y - offset); // Relative positions element
this.header = header; // Assigns
}
get_value() {
let value = this.elem.value();
console.log(value);
}
}
class Button {
constructor(x, y, label="") {
// Attributes
this.elem = null; // Button
this.create_elem(x, y, label);
}
// Methods
create_elem(x, y, label) {
let button = createButton(label); // Creates 'button' element
button.position(x, y); // Positions element
button.parent("main_canvas"); // Requires an HTML element in 'index.html' file
// 'main_canvas' is that element 'id'
this.elem = button; // Assigns
}
pressed() {
let value = input.get_value(); // Gets global 'input' value (filled by user)
console.log(value);
}
}
class Slider {
constructor(x, y, size=100) {
// Attributes
this.elem = null; // Slider
this.create_elem(x, y, size);
}
// Methods
create_elem(x, y, size) {
let slider = createSlider(0, size, 0, 1); // Creates 'slider' element
slider.position(x, y); // Positions element
slider.parent("main_canvas"); // Requires an HTML element in 'index.html' file
// 'main_canvas' is that element 'id'
this.elem = slider; // Assigns
}
get_value() {
let value = this.elem.value();
return value;
}
show(font_size=16, label_offset=30) { // Draws the label (not the element)
let value = this.get_value();
push(); // Style: Text
fill(0);
textSize(font_size);
textFont("Arial");
textAlign(CENTER, CENTER);
text(value, this.elem.x + this.elem.width + label_offset, this.elem.y + 2*this.elem.height/3);
pop();
}
}
class Checkbox {
constructor(x, y, label="") {
// Attributes
this.elem = null; // Checkbox
this.create_elem(x, y, label);
}
// Methods
create_elem(x, y, label) {
let checkbox = createCheckbox(label); // Creates 'checkbox' element
checkbox.position(x, y); // Positions element
checkbox.parent("main_canvas"); // Requires an HTML element in 'index.html' file
// 'main_canvas' is that element 'id'
this.elem = checkbox; // Assigns
}
get_value() {
let bool = this.elem.checked();
return bool;
}
show(font_size=16, label_offset=20) { // Draws the label (not the element)
let bool_str = this.get_value();
push(); // Style: Text
fill(0);
textSize(font_size);
textFont("Arial");
textAlign(LEFT, CENTER);
text(bool_str, this.elem.x + this.elem.width/4 + label_offset, this.elem.y + this.elem.height/2); // 'this.elem.width/4': compensating for object's high width
pop();
}
}
class Select {
constructor(x, y) {
// Attributes
this.elem = null; // Checkbox
this.create_elem(x, y);
}
// Methods
create_elem(x, y) {
let checkbox = createSelect(); // Creates 'select' element
checkbox.position(x, y); // Positions element
checkbox.parent("main_canvas"); // Requires an HTML element in 'index.html' file
// 'main_canvas' is that element 'id'
this.elem = checkbox; // Assigns
}
add_option(label) {
this.elem.option(label); // Adds a single option
}
add_options(labels_lst) {
for (let label of labels_lst) { // Adds bulk options
this.elem.option(label);
}
}
set_value(label) {
this.elem.selected(label); // Sets the selected option
}
get_value() {
let value = this.elem.value();
return value;
}
show(font_size=16, label_offset=50) { // Draws the label (not the element)
let value = this.get_value();
push(); // Style: Text
fill(0);
textSize(font_size);
textFont("Arial");
textAlign(LEFT, CENTER);
text(value, this.elem.x + this.elem.width + label_offset, this.elem.y + this.elem.height/2); // 'this.elem.width/2': compensating for object's high width
pop();
}
}
class Radio {
constructor(x, y, size) {
// Attributes
this.elem = null; // Checkbox
this.create_elem(x, y, size);
}
// Methods
create_elem(x, y, size=65) {
let radio = createRadio(); // Creates 'radio' element
radio.position(x, y); // Positions element
radio.style("width", "60px"); // Important: if 'width' is:
// too small: options breaks lines
// too big: options share same line
radio.style("fontFamily", "Arial"); // Changes font type (values as strings like in CSS)
radio.style("fontSize", "12px"); // Changes font size (values as strings like in CSS)
radio.parent("main_canvas"); // Requires an HTML element in 'index.html' file
// 'main_canvas' is that element 'id'
this.elem = radio; // Assigns
}
add_option(label) {
this.elem.option(label); // Adds a single option
}
add_options(labels_lst) {
for (let label of labels_lst) { // Adds bulk options
this.elem.option(label);
}
}
set_value(label) {
this.elem.selected(label); // Sets the selected option
}
get_value() {
let value = this.elem.value();
return value;
}
show(font_size=16, label_offset=10) { // Draws the label (not the element)
let value = this.get_value();
push(); // Style: Text
fill(0);
textSize(font_size);
textFont("Arial");
textAlign(LEFT, CENTER);
text(value, this.elem.x + this.elem.width + label_offset, 1.125*this.elem.y); // 'this.elem': broken '.height' is 0
pop();
}
}
// User-Defined Functions
// p5 Main
function setup() {
canvas = createCanvas(width, height); // Canvas reference
input = new Input(20, 50, "'input' Element"); // Instantiates 'Input' class
button = new Button(20, 80, "Print 'input'"); // Instantiates 'Button' class
button.elem.mousePressed(button.pressed); // Important: 'mousePRessed' is available for the element (not instance itself)
slider = new Slider(20, 140, 100); // Instantiates 'Slider' class
checkbox = new Checkbox(20, 190, "Checkbox"); // Instantiates 'Checkbox' class
select_elem = new Select(20, 240); // Instantiates 'Select' class
select_elem.add_option("Red"); // Adds 1 option
select_elem.add_options(["Blue", "Green", "Yellow"]); // Adds multiple options
select_elem.set_value("Blue"); // Sets option
radio = new Radio(20, 280); // Instantiates 'Radio' class
radio.add_option("Red"); // Adds 1 option
radio.add_options(["Blue", "Green", "Yellow"]); // Adds multiple options
radio.set_value("Green"); // Sets option
}
function draw() {
// Main
background(250); // Grayscale white
slider.show(); // Slider value
checkbox.show(); // Checkbox value
select_elem.show(); // Select value
radio.show(); // Radio value
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<audio id="audio">
<source src="sound/music.mp3" type="">
</audio>
<button id="play">播放</button>
<button id="pause">暂停</button>
<button id="toggleAudio">播放/暂停</button>
<script type="text/javascript">
// var audioEle=document.getElementById('audio');
// var playControl=function(id){
// this.videoplay=function(){
// id.play();
// }
// this.videopause=function(){
// id.pause();
// }
// this.toggleAudio=function(){
// id.paused?id.play():id.pause();
// }
// }
// var oPlay=document.getElementById('play');
// var oPause=document.getElementById('pause');
// var oToggleAudio=document.getElementById('toggleAudio');
// var obj=new playControl(audioEle);
// oPlay.addEventListener('click', obj.videoplay, false);
// oPause.addEventListener('click', obj.videopause, false);
// oToggleAudio.addEventListener('click',obj.toggleAudio,false);
function Person(name,age){
this.name=name;
this.age=age;
//以下这种定义方式会造成子类构造函数调用时复制一个新的方法,造成资源浪费
this.getAge=function(){
console.log("Hi,I'm "+this.age+' years old!');
}
}
Person.prototype.getName=function(){
console.log("Hi,I'am "+this.name+'!');
}
function Students(classId,name,age){
Person.call(this,name,age);
this.classId=classId;
this.introduce=function(){
console.log("Hi,I'm "+this.name+","+this.age+"years old!"+"from "+this.classId+"class!");
}
}
// 55 56不能换位置 为了让Students能够使用Person定义的getName方法:71行,73为TRUE代表两个类共用的一个getName方法
Students.prototype=Object.create(Person.prototype); //Students.prototype=new Person(); Object.create更常用
Students.prototype.showGrade=function(grade){
console.log(this.name+"'s math grade is "+grade);
}
var obj=new Person("teen",26);
obj.getAge();
console.log(obj.name);
obj.getName();
var obj2=new Person("amy",20);
obj2.getName();
var sObj=new Students(100822,"teen",30);
sObj.introduce();
sObj.showGrade(99);
sObj.showGrade(100);
sObj.getAge();
sObj.getName();
console.log(sObj.getAge==obj.getAge);
console.log(sObj.getName==obj.getName);
//2、私有共有变量
// function Person(firstName, lastName, age)
// {
// //私有变量:
// var _firstName = firstName;
// var _lastName = lastName;
// //公共变量:
// this.age = age;
// //方法:
// this.getName = function()
// {
// // return(firstName + " " + lastName);
// alert(firstName + " " + lastName);
// };
// this.SayHello = function()
// {
// alert("Hello, I'm " + firstName + " " + lastName);
// };
// };
// var BillGates = new Person("Bill", "Gates", 53);
// var SteveJobs = new Person("Steve", "Jobs", 53);
// BillGates.SayHello();
// SteveJobs.SayHello();
// // alert(BillGates.getName() + " " + BillGates.age);
// alert(BillGates._firstName);
// BillGates.getName();
//3、
// var object = //定义小写的object基本类,用于实现最基础的方法等
// {
// isA: function(aType) //一个判断类与类之间以及对象与类之间关系的基础方法
// {
// var self = this;
// while(self)
// {
// if (self == aType)
// return true;
// self = self.Type;
// };
// return false;
// }
// };
// function Class(aBaseClass, aClassDefine) //创建类的函数,用于声明类及继承关系
// {
// function class_() //创建类的临时函数壳
// {
// this.Type = aBaseClass; //我们给每一个类约定一个Type属性,引用其继承的类
// for(var member in aClassDefine)
// this[member] = aClassDefine[member]; //复制类的全部定义到当前创建的类
// };
// class_.prototype = aBaseClass;
// return new class_();
// };
// function New(aClass, aParams) //创建对象的函数,用于任意类的对象创建
// {
// function new_() //创建对象的临时函数壳
// {
// this.Type = aClass; //我们也给每一个对象约定一个Type属性,据此可以访问到对象所属的类
// if (aClass.Create)
// aClass.Create.apply(this, aParams); //我们约定所有类的构造函数都叫Create,这和DELPHI比较相似
// };
// new_.prototype = aClass;
// return new new_();
// };
// //语法甘露的应用效果:
// var Person = Class(object, //派生至object基本类
// {
// Create: function(name, age)
// {
// this.name = name;
// this.age = age;
// },
// SayHello: function()
// {
// alert("Hello, I'm " + this.name + ", " + this.age + " years old.");
// }
// });
// var Employee = Class(Person, //派生至Person类,是不是和一般对象语言很相似?
// {
// Create: function(name, age, salary)
// {
// Person.Create.call(this, name, age); //调用基类的构造函数
// this.salary = salary;
// },
// ShowMeTheMoney: function()
// {
// alert(this.name + " $" + this.salary);
// }
// });
// var BillGates = New(Person, ["Bill Gates", 53]);
// var SteveJobs = New(Employee, ["Steve Jobs", 53, 1234]);
// BillGates.SayHello();
// SteveJobs.SayHello();
// SteveJobs.ShowMeTheMoney();
// var LittleBill = New(BillGates.Type, ["Little Bill", 6]); //根据BillGate的类型创建LittleBill
// LittleBill.SayHello();
// alert(BillGates.isA(Person)); //true
// alert(BillGates.isA(Employee)); //false
// alert(SteveJobs.isA(Person)); //true
// alert(Person.isA(Employee)); //false
// alert(Employee.isA(Person));
</script>
</body>
</html>
|
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js";
import { useEffect, useState } from "react";
import useAxiosAction from "../../../Components/AxiosAction/useAxiosAction";
import AuthProvider, { authContext } from "../../../Authentication/authProvider/AuthProvider";
import './checkout.css'
import Swal from "sweetalert2";
const CheckoutPage = ({ price, currentClass }) => {
// console.log(price);
const stripe = useStripe();
const elements = useElements();
const axiosAction = useAxiosAction();
const { user } = AuthProvider(authContext)
const [cardError, setError] = useState(null)
const [clientSecret, setClientSecret] = useState("");
const [loading, setLoading] = useState(false);
useEffect(() => {
axiosAction.post("/create-payment-intent", { price })
.then(res => {
setClientSecret(res.data.clientSecret)
})
// fetch("/create-payment-intent", {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify({ price }),
// })
// .then((res) => res.json())
// .then((data) => setClientSecret(data.clientSecret));
}, [price, axiosAction])
const handleSubmit = async (event) => {
event.preventDefault();
if (!stripe || !elements) {
return;
}
const card = elements.getElement(CardElement);
if (card == null) {
return;
}
const { error } = await stripe.createPaymentMethod({
type: 'card',
card,
});
if (error) {
setError(error.message)
}
const { paymentIntent, error: confirmError } = await stripe.confirmCardPayment(
clientSecret,
{
payment_method: {
card: card,
billing_details: {
name: user?.displayName,
email: user?.email
},
},
},
);
if (confirmError) {
setError(confirmError);
}
// console.log(paymentIntent)
if (paymentIntent.status === "succeeded") {
setLoading(true);
// console.log(paymentIntent.currency)
delete currentClass._id
currentClass.transactionId = paymentIntent.id;
// console.log(currentClass, paymentIntent)
axiosAction.post('/payment', currentClass)
.then(res => {
if (res.data.insertedId) {
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'payment complete',
showConfirmButton: false,
})
}
})
}
// console.log(transID)
// console.log(cardError)
}
return (
<section className="ms-5">
<form className="w-3/4" onSubmit={handleSubmit}>
<CardElement
options={{
style: {
base: {
fontSize: '16px',
color: '#424770',
'::placeholder': {
color: '#aab7c4',
},
},
invalid: {
color: '#9e2146',
},
},
}}
/>
<button className="btn btn-success btn-sm my-6" type="submit" disabled={!stripe || !clientSecret || loading}>
Pay
</button>
{cardError && <p className="text-red-600 font-bold text-center">{cardError.message}</p>}
</form>
</section>
);
};
export default CheckoutPage;
|
package tests;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.shaft.driver.DriverFactory;
import com.shaft.driver.DriverFactory.DriverType;
import com.shaft.gui.element.ElementActions;
import pages.HomePage;
import pages.ProfilePage;
import pages.RegisterationPage;
public class RegisterationGridTest{
public static String BaseUrl = "https://qc.yaschools.com/";
public static String hubUrl = "http://localhost:4444/wd/hub";
WebDriver driver = DriverFactory.getDriver(DriverType.DESKTOP_CHROME);
HomePage homePageObject;
RegisterationPage registerPageObject;
ProfilePage profilePageObject;
String fullName = "somia Hasab ELnabi";
String email = "somia1100@gmail.com";
String password = "123456789";
@BeforeTest
//@Parameters(value={"browserName"})
public void setup(){
DesiredCapabilities caps = new DesiredCapabilities();
caps.setBrowserName("chrome");
// try {
// driver = new RemoteWebDriver(new URL(hubUrl), caps);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
driver.navigate().to(BaseUrl);
}
@Test
//User Can Register With Valid Data
public void userRegisterWithValidInput(){
homePageObject = new HomePage(driver);
registerPageObject = new RegisterationPage(driver);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(homePageObject.closeAnnouncementForm));
ElementActions.click(driver, homePageObject.closeAnnouncementForm);
ElementActions.click(driver,homePageObject.registerationBtn);
registerPageObject.userRegistration(fullName,email,password,password);
assertEquals(ElementActions.getText(driver, homePageObject.alertConfirmationMsg),
"تم انشاء الحساب بنجاح .من فضلك افحص البريد الإلكتروني لتفعيل الحساب");
}
@AfterTest
public void tearDown() {
driver.quit();
}
}
|
from rest_framework import serializers
from rest_framework.request import Request
from myapp.models import Blog
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = ['id', 'title', 'content', 'created_at', 'modified_at', 'author']
read_only_fields = ['author']
def create(self, validated_data):
# Automatically set the author to the authenticated user during creation
request = self.context.get('request') # Access the request object
validated_data['author'] = request.user # Set the author
return super().create(validated_data)
def get_author(self, obj):
return obj.author.username if obj.author else None
def to_representation(self, obj):
representation = super().to_representation(obj)
representation['author'] = obj.author.username
return representation
|
package fizzbuzz;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.Before;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class FizzBuzzDivisibleByFiveTest {
private Integer num;
private String expectedResult;
private FizzBuzz fizzbuzz;
@Before
public void initialize() {
fizzbuzz = new FizzBuzz();
}
public FizzBuzzDivisibleByFiveTest(Integer num, String expectedResult) {
this.num = num;
this.expectedResult = expectedResult;
}
@Parameterized.Parameters
public static Collection nums() {
return Arrays.asList(new Object[][] {
{5, "buzz"},
{10, "buzz"},
{20, "buzz"},
{50, "buzz"},
{700, "buzz"},
});
}
@Test
public void returnsBuzzWhenDivisibleByFive() {
assertEquals(expectedResult, fizzbuzz.testDivisors(num));
}
}
|
# Kubeadm
## 0. 全局变量
```
K8S_NFS=/home/ervin/k8s-nfs
NODE_1=master1
NODE_2=master2
NODE_3=master3
NODE_4=worker1
WORKER_1=worker1
IP_1=192.168.1.1
IP_2=192.168.1.2
IP_3=192.168.1.3
IP_NFS=192.168.1.10
NFS_DIR=/home/ervin/data
USER=ervin
USER_DIR=/home/ervin
```
## 1. 更新master主节点证书
```
mkdir -p ${K8S_NFS}/config
mkdir -p ${K8S_NFS}/worker-config
mkdir -p ${K8S_NFS}/join
mkdir -p ${K8S_NFS}/worker-certs
mkdir -p ${K8S_NFS}/master-certs
# 集群资源清单(生成后取clusterConfiguration里面的内容)
kubectl -n kube-system get cm kubeadm-config -o yaml > ${K8S_NFS}/config/kubeadm-config-init.yaml
# 查看证书有效期
for i in $(ls /etc/kubernetes/pki/*.crt /etc/kubernetes/pki/etcd/*.crt); do echo "===== $i ====="; openssl x509 -in $i -text -noout | grep -A 3 'Validity' ; done
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -text |grep Not
openssl x509 -in /var/lib/kubelet/pki/kubelet-client-current.pem -noout -text |grep Not
kubeadm certs check-expiration
# 备份证书
cp -a /etc/kubernetes{,.bak}
cp -a /var/lib/kubelet{,.bak}
cp -a /var/lib/etcd /var/lib/etcd.bak
# 更新
kubeadm certs renew all --config=${K8S_NFS}/config/kubeadm-config-init.yaml
stat apiserver.key apiserver.crt
# 重新生成配置
rm -rf /etc/kubernetes/*.conf
kubeadm init phase kubeconfig all --config=${K8S_NFS}/config/kubeadm-config-init.yaml
ls -alh /etc/kubernetes/*.conf
kubeadm init phase kubeconfig all --node-name ${NODE_2} --kubeconfig-dir ${K8S_NFS}/worker-config/${NODE_2}
kubeadm init phase kubeconfig all --node-name ${NODE_3} --kubeconfig-dir ${K8S_NFS}/worker-config/${NODE_3}
# 新配置复制到用户目录
mkdir -p ${USER_DIR}/.kube
cp -i /etc/kubernetes/admin.conf ${USER_DIR}/.kube/config
chown ${USER}:${USER} ${USER_DIR}/.kube/config
mkdir -p /root/.kube
cp -i /etc/kubernetes/admin.conf /root/.kube/config
# 重启组件
docker ps |grep -E 'k8s_kube-apiserver|k8s_kube-controller-manager|k8s_kube-scheduler' | awk -F ' ' '{print $1}' |xargs docker restart
#kubectl -n kube-system delete pod -l 'component=kube-apiserver'
#kubectl -n kube-system delete pod -l 'component=kube-controller-manager'
#kubectl -n kube-system delete pod -l 'component=kube-scheduler'
#kubectl -n kube-system delete pod -l 'component=etcd'
# 重启kubelet
rm -rf /var/lib/kubelet/pki/kubelet-client-*
systemctl restart kubelet.service
# 验证
systemctl status -l kubelet.service
journalctl -xefu kubelet
ls -alh /var/lib/kubelet/pki/kubelet-client-current.pem
kubectl get pod -n kube-system | egrep "kube-apiserver|kube-controller-manager|kube-scheduler|etcd"
kubectl get cs
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -text |grep ' Not '
# 新证书放到nfs
cp -av /etc/kubernetes/* ${K8S_NFS}/master-certs
```
## 2.1 master主节点后续操作(生成token)
```
# 生成加入token命令【TOKEN】
#kubeadm token list
kubeadm token create --print-join-command > ${K8S_NFS}/join/join-master.sh
cp ${K8S_NFS}/join/join-master.sh ${K8S_NFS}/join/join-worker.sh
# 获取CA证书公钥哈希值(加入命令里已有)【CA_HASH】
#openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^ .* //'ls
# 生成certificate-key【CERT_KEY】
" --control-plane --certificate-key " >> ${K8S_NFS}/join/join-master.sh
kubeadm init phase upload-certs --upload-certs >> ${K8S_NFS}/join/join-master.sh
# 即组合命令:kubeadm join ${NODE_1}:6443 --token ${TOKEN} \
--discovery-token-ca-cert-hash sha256:${CA_HASH} \
--control-plane --certificate-key ${CERT_KEY}
# 检查master节点情况
curl -ik https://${NODE_1}:6443/version
# 生成worker证书
kubeadm init phase kubeconfig kubelet --node-name ${NODE_4} --kubeconfig-dir ${K8S_NFS}/worker-certs --config ${K8S_NFS}/config/kubeadm-config-init.yaml
```
## 2.2 master主节点后续操作(如需重置节点)
```
# 若内置etcd
kubectl exec -n kube-system -it etcd-xxxPodName /bin/sh
etcdctl --endpoints 127.0.0.1:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/server.crt --key /etc/kubernetes/pki/etcd/server.key member list
etcdctl --endpoints https://${IP_1}:2379,https://${IP_2}:2379,https://${IP_3}:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/server.crt --key /etc/kubernetes/pki/etcd/server.key endpoint status
etcdctl --endpoints 127.0.0.1:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/server.crt --key /etc/kubernetes/pki/etcd/server.key member remove 要移除的旧节点Id
# 移除从master
kubectl drain ${NODE_1} --delete-local-data --delete-emptydir-data --force --ignore-daemonsets
kubectl delete node ${NODE_1}
kubectl drain ${NODE_1} --delete-local-data --delete-emptydir-data --force --ignore-daemonsets
kubectl delete node ${NODE_1}
# 移除worker
#kubectl cordon NODE_4
#kubectl drain NODE_4 --delete-emptydir-data --force --ignore-daemonsets
```
## 2.3 节点清理(需要重置的节点做)
```
# docker
docker stop `docker ps -aq`
systemctl stop docker
systemctl restart docker
docker container prune
# k8s
#echo y | kubeadm reset
systemctl stop kubelet
rm -rf /root/.kube
rm -rf ${USER_DIR}/.kube
rm -rf /var/lib/cni/ /var/lib/kubelet/* /etc/cni/
# 移除不了就reboot,然后重新挂载nfs
# nfs挂载方式见nfs.md
# mount -t nfs ${IP_NFS}:${NFS_DIR} ${K8S_NFS}
# 网络
ip link set cni0 down && ip link set flannel.1 down
ip link delete cni0 && ip link delete flannel.1
ipvsadm --clear
iptables -F && iptables -t nat -F && iptables -t mangle -F && iptables -X
```
## 3.1 master从节点加入(重置后)- 方法1
```
# 先做节点清理
# 证书清理 & 复制
rm /etc/kubernetes/*
mkdir -p /etc/kubernetes/manifests
cp -av ${K8S_NFS}/master-certs/admin.conf /etc/kubernetes/admin.conf
cp -av ${K8S_NFS}/master-certs/pki /etc/kubernetes/pki
rm -rf /etc/kubernetes/pki/apiserver*
# 加入节点
systemctl enable kubelet
sh ${K8S_NFS}/join/join-master.sh
# 新配置复制到用户目录
mkdir -p ${USER_DIR}/.kube
cp -i /etc/kubernetes/admin.conf ${USER_DIR}/.kube/config
chown ${USER}:${USER} ${USER_DIR}/.kube/config
mkdir -p /root/.kube
cp -i /etc/kubernetes/admin.conf /root/.kube/config
```
## 3.2 master从节点加入(重置后)- 方法2
```
# 加入节点
vim ${K8S_NFS}/join/join-k8s.yaml
apiVersion: kubeadm.k8s.io/v1beta3
caCertPath: /etc/kubernetes/pki/ca.crt
discovery:
bootstrapToken:
apiServerEndpoint: ${IP_1}:6443 # 高可用的APIServer地址
token: ${TOKEN} # 上述步骤生成Token
caCertHashes:
- "sha256:${CA_HASH}" # 上述步骤获取到的CA(证书)公钥哈希值
timeout: 5m0s
kind: JoinConfiguration
controlPlane:
certificateKey: ${CERT_KEY} # 上述步骤获取到 certificate key
localAPIEndpoint:
advertiseAddress: ${IP_2} # 本地APIServer节点地址
bindPort: 6443 # 本地APIServer节点端口
nodeRegistration:
criSocket: /var/run/dockershim.sock
imagePullPolicy: IfNotPresent
name: ${NODE_2} # 重点,节点名称
taints:
- effect: NoSchedule
key: node-role.kubernetes.io/master
kubeadm join --config=${K8S_NFS}/join/join-k8s.yaml --v=5
```
## 4.1 worker节点加入(重置后)- 方法1
```
# 先做节点清理
sh ${K8S_NFS}/join/join-worker.sh
```
## 4.2 worker节点加入(重置后)- 方法2
```
# 加入(方法2)
tee > ${K8S_NFS}/join/join-k8s-worker.yaml <<EOF
apiVersion: kubeadm.k8s.io/v1beta3
caCertPath: /etc/kubernetes/pki/ca.crt
discovery:
bootstrapToken:
apiServerEndpoint: ${NODE_1}:6443
token: ${TOKEN}
unsafeSkipCAVerification: true
timeout: 5m0s
tlsBootstrapToken: ${TOKEN}
kind: JoinConfiguration
nodeRegistration:
#criSocket: /run/containerd/containerd.sock
cruSocket: /var/run/dockershim.sock
imagePullPolicy: IfNotPresent
name: ${WORKER_1}
taints: null
EOF
kubeadm join --config=${K8S_NFS}/join/join-k8s-worker.yaml --v=5
# 查看
kubectl label nodes ${WORKER_1} node-role.kubernetes.io/work=test
kubectl get nodes ${WORKER_1}
```
## 5. worker证书更新
```
# 对应xxNode的证书
cp -av ${K8S_NFS}/worker-certs/kubelet.conf /etc/kubernetes/kubelet.conf
# 重启
systemctl restart kubelet
# 验证
openssl x509 -in /var/lib/kubelet/pki/kubelet-client-current.pem -noout -text |grep Not
```
## 6. master从节点证书更新(不重置-TODO)
```
```
## 7. worker证书更新(不重置-TODO)
```
```
## 8. 报错解决
### (1)The connection to the server localhost:8080 was refused
```
# 方法1
mkdir -p $HOME/.kube
echo 'yes' | sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
# 方法2
export KUBECONFIG=/etc/kubernetes/admin.conf:~/.kube/devops.kubeconfig
# 方法3
kubectl config --kubeconfig=/etc/kubernetes/admin.conf
```
### (2)connect: connection refusedcalico/node is not ready
```
# 方法1:改yaml配置清单
spec.containers.env 下添加以下两行
- name: IP_AUTODETECTION_METHOD
value: "interface=ens.*" # ens 根据实际网卡开头配置
# 方法2:删网卡
ifconfig br-xxx down
# 方法3:用containerd的情况下卸载docker
sudo apt-get autoremove docker docker-ce docker-engine docker.io
kubectl delete pod -n kube-system calico-node-xxx
```
### (3) bridge-nf-call-iptables does not exist
```
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
modprobe br_netfilter && sudo sysctl --system
```
### (4) Unable to read config path" err="path does not exist, ignoring
```
mkdir -vp /etc/kubernetes/manifests
```
### (5) the namespace "kube-system" error downloading the secret
```
kubeadm init phase upload-certs --upload-certs
```
## 9. 脚本更新证书
```
# 更新
chmod +x update-kubeadm-cert.sh
./update-kubeadm-cert.sh all
# 验证
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -text | grep Not
kubeadm certs check-expiration
# 更新(不带etcd)
chmod +x update-kubeadm-cert.sh
./update-kubeadm-cert.sh master
```
|
<template>
<v-row>
<v-col cols="12" lg="12" xs="12">
<!-- <h1>{{ quiz.quizName }}</h1> -->
<Question
v-if="currentQuestion"
:question="currentQuestion.questionText"
:answers="currentQuestion.answers"
@answer-selected="handleAnswerSelected"
/>
</v-col>
</v-row>
</template>
<script>
import { useQuizStore } from '../store/quiz'
import { computed, onMounted } from 'vue'
import Question from '../components/questions/Question.vue'
export default {
components: {
Question
},
setup() {
const quizStore = useQuizStore()
const quiz = computed(() => quizStore.getQuiz)
const currentQuestion = computed(() => quizStore.getCurrentQuestion)
onMounted(() => quizStore.fetchQuizById())
function handleAnswerSelected(index) {
setTimeout(() => {
quizStore.displayNextQuestion()
}, 1000)
}
return { quiz, currentQuestion, handleAnswerSelected }
}
}
</script>
|
import { useCallback, useEffect, useState } from "react"
import { ShowIncrement } from "./ShowIncrement";
export const CallbackHook = () => {
const [counter, setCounter] = useState(10);
const increment = useCallback(
(value) => {
setCounter((c) => c + value)
},[]
)
useEffect(() => {
increment()
}, [increment])
return (
<>
<h1>UseCallBack Hook: { counter }</h1>
<hr/>
<ShowIncrement increment={increment}/>
</>
)
}
|
#grid-content.hidden
label for='default-length' default row length:
input{
type='number'
id='default-row-length'
name='default-length'
min='1'
max='32'
step='1'
value='4'
}
br
label for='bpm' bpm:
input{
type='number'
id='bpm'
name='bpm'
min='1'
max='500'
step='1'
value='120'
}
br
label for='division' division:
select id='division' name='division'
option value='1' whole notes
option value='2' half notes
option value='3' quarter note triplets
option selected='selected' value='4' quarter notes
option value='6' eighth note triplets
option value='8' eighth notes
option value='12' sixteenth note triplets
option value='16' sixteenth notes
br
button#record-grid record
br
button#play-grid play
br
button#add-row add row
br
#grid-cell-modal.hidden
select#grid-cell-options
#rows
coffee:
# Static handles of DOM elements
$grid_content = $ "#grid-content"
$add_row = $grid_content.find "#add-row"
$play_grid = $grid_content.find "#play-grid"
$record_grid = $grid_content.find "#record-grid"
$rows = $grid_content.find "#rows"
$bpm = $grid_content.find "#bpm"
$division = $grid_content.find "#division"
$default_row_length = $grid_content.find "#default-row-length"
# Crafts HTML for a column in the grid.
build_col = (row_idx, col_idx) ->
$ """
<li data-row-idx='#{row_idx}' data-idx='#{col_idx}' class='col'>
<span class='col-text'></span>
<section class='hidden grid-cell-audio'>
</section>
</li>
"""
# When a column is clicked, a modal should appear to select the recording to
# play at that grid slot.
# In it's current state this isn't actually a modal, but rather a dropdown
# that gets temporarily placed inside the column box.
show_modal = ($col) ->
$opts = $("#audio-selector").clone()
$grid_cell_audio = $col.find(".grid-cell-audio")
$modal = $ """
<div class='col-opts-modal'>
</div>
"""
$.each $opts.find("option:selected"), (idx, node) ->
node.removeAttribute "selected"
$opts.prepend $ """
<option disabled selected value> -- select an option -- </option>
"""
$modal.append $opts
$opts.on "change", ->
$selected = $opts.find("option:selected")
filename = $selected.val()
common_name = $selected.text()
row_idx = ~~$col.data("row-idx")
col_idx = ~~$col.data("idx")
row = state.grid_matrix[row_idx]
row[col_idx] = { cmd: "note", filename }
$col.addClass("has-content")
$col.attr("title", common_name)
$audio = $(".audio[data-filename='#{filename}'] audio").clone()
$audio.addClass("hidden")
$grid_cell_audio.empty().append $audio
$modal.remove()
$modal
# Event listeners for columns.
add_col_events = ($col, row_idx, col_idx) ->
$text = $col.find(".col-text")
$col.on "click", ->
if $col.hasClass("has-content")
$col.attr("title", "")
$col.text ""
$col.removeClass("has-content")
state.grid_matrix[row_idx][col_idx] = {cmd: "rest"}
$col.find(".grid-cell-audio").empty()
else
return if $col.find(".col-opts-modal").length > 0
$open_modal = show_modal($col)
$col.prepend $open_modal
$col.on "mouseenter", ->
if $col.hasClass("has-content")
$text.text "x"
true
$col.on "mouseleave", ->
$text.text ""
true
# Columns are temporary things in this grid implementation.
# Whenever the number of columns in a row changes,
# all of the columns in the row are deleted and new ones generated.
# This method handles that, as well as setting up the initial state of a row.
# It creates the columns' HTML and attaches them to the DOM.
set_num_cols = (row_idx, num_cols, $rows, $row_wrapper, $ul) ->
state.grid_matrix[row_idx] = ((array) ->
[0...num_cols].forEach -> array.push {cmd: "rest"}
array
)([])
grid_state.$containers[row_idx] = []
[0...num_cols].forEach (col_idx) ->
$col = build_col(row_idx, col_idx)
$ul.append $col
add_col_events($col, row_idx, col_idx)
grid_state.$containers[row_idx].push $col
$rows.append $row_wrapper
# Builds HTML for a row.
# This is only run when the 'add row' button is clicked.
build_row = (idx) ->
$ """
<div class='row-wrapper'>
<ul class='row' data-idx='#{idx}' ></ul>
<button class='remove-row'>X</button>
<label for='num-cols'> beats: </label>
<input
type='number'
name='num-cols'
class='num-cols'
></input>
</div>
</div>
"""
# State tracking for the grid, in a global variable.
# This is the private state of the grid.
# The public interface (state.grid_matrix) is only used to store commands,
# everything else happens here.
# For example if there was 1 row with 2 columns,
# state.grid matrix could be [[{cmd: "rest"}, {cmd: "play", filename: "foo"}]]
# and grid_state would contain references to the grid's audio context, recording
# stream, column nodes, audio nodes, per-row indexes, and play/stop state.
# As for why per-row indexes are stored; that's so the grid can be polyrhythmic.
# For example if one row has 3 columns and another row has 4, then they
# should only play the first column together every 3 repetitions.
# The grid gets it's own audio context (which should in the future be removed,
# and the existing audio context used) and thus another recorder, which gets
# event listeners declared here.
window.grid_state = (->
context = new AudioContext()
stream = context.createMediaStreamDestination()
recorder = new MediaRecorder(stream.stream)
stream.connect context.destination
recorder.onerror = (e) ->
console.log "GRID RECORD ERROR"
throw e
recorder.ondataavailable = (e) ->
grid_state.recording_chunks.push e.data
recorder.onstop = (e) ->
blob = new Blob grid_state.recording_chunks,
type: 'audio/ogg; codecs=opus'
filename = "#{Utils.random_string()}.webm"
db.store_audio(blob, filename)
{
context, stream, recorder
col_idxs: []
audios: {}
last_row_idx: -1
$containers: []
stopping: false
recording_chunks: []
}
)()
# Every N frames (where N is dynamically calculated by the BPM/division settings)
# the next column in each row gets played.
#
# This function plays the columns, then increments the indexes.
# The incrementing happens optimistically, so there's a nil check which resets
# the index to zero if no column exists at that index
#
# Something similar is used to handle rows being deleted during playback.
# The deletion in grid_state happens optimistically, and if state.grid_matrix
# requests a row which doesn't exist, then state.grid_matrix is updated.
play_next_note = ->
missing_rows = []
state.grid_matrix.forEach (row, row_idx) ->
col_idx = grid_state.col_idxs[row_idx]
col = row[col_idx]
if !col
col_idx = 0
grid_state.col_idxs[row_idx] = col_idx
col = row[col_idx]
containers_row = grid_state.$containers[row_idx]
$last_col = if col_idx == 0
containers_row[(containers_row.length) - 1]
else
containers_row[col_idx - 1]
$last_col.removeClass("playing")
unless grid_state.$containers[row_idx]
missing_rows.push row_idx
return
$container = grid_state.$containers[row_idx][col_idx]
$container.addClass("playing")
switch col.cmd
when "rest"
null
when "note"
aud = grid_state.audios[col.filename]
aud ||= add_grid_audio_ref(
$(".audios audio[filename='#{col.filename}']")[0]
)
aud.pause()
aud.currentTime = 0
aud.play()
grid_state.col_idxs[row_idx] += 1
missing_rows.sort().reverse().forEach (idx) ->
state.grid_matrix.splice(idx, 1)
# Most of the grid data is stored in matrices,
# so indices are automatically adjusted upon row removal,
# but the data on the DOM has to be manually changed.
fix_containers_after_removal = (row_idx) ->
all_idxs = [0...(grid_state.$containers.length + 1)]
to_fix = all_idxs.filter (num) -> num > row_idx
to_fix.forEach (idx) ->
$containers = grid_state.$containers[idx - 1]
$containers[0].parent(".row").data("idx", idx - 1)
$containers.forEach ($container) ->
$container.attr("data-row-idx", idx - 1)
grid_state.last_row_idx -= 1
# Sets the column indexes to 0, both visually and in the grid_state
reset_grid_state = ->
$(".col.playing").removeClass "playing"
grid_state.col_idxs.forEach (_, row_idx) ->
grid_state.col_idxs[row_idx] = 0
grid_state.$containers[row_idx][0].addClass "playing"
# Called every animation frame, determines based on the provided "ticks_gap"
# (the number of ms to wait between playing columns) whether to move forward in
# the grid.
grid_tick = (ticks_gap, idx) ->
->
if [ticks_gap, 0].includes(idx)
play_next_note(idx)
idx += 1
(idx = 0) if idx >= (ticks_gap * 2)
if grid_state.stopping
grid_state.stopping = false
reset_grid_state()
else
requestAnimationFrame grid_tick(ticks_gap, idx)
# When a recording is attached to a column, a hidden audio node is created
# which gets attached to the grid recorder.
add_grid_audio_ref = (audio) ->
{ context, stream } = grid_state
audio_clone = $(audio).clone()[0]
grid_state.audios[$(audio).data("filename")] = audio_clone
audio_clone.loop = false
source = context.createMediaElementSource audio_clone
source.connect context.destination
source.connect stream
audio_clone
# When the 'play grid' button is clicked, the DOM is parsed for bpm/division
# which is used to call grid_tick (invoked in an animation frame request)
#
# NOTE looks to be a small bug in here, add_grid_audio_ref should be cached
play_grid = ->
return true if state.grid_matrix.length < 1
bpm = parseFloat($bpm.val())
console.log bpm, "bpm"
division = parseFloat($division.find("option:selected").val() || 120)
console.log division, "division"
seconds_gap = 240 / (bpm * division)
console.log seconds_gap, "seconds gap"
ticks_gap = seconds_gap * 60.0
console.log ticks_gap, "ticks gap"
$audios = $(".audio audio")
$.each $(".row"), (row_idx, row_node) ->
row = grid_state.$containers[row_idx]
$.each $(row_node).find(".col"), (col_idx, col) ->
row.push $(col)
$.each $audios, (idx, audio) ->
add_grid_audio_ref(audio)
requestAnimationFrame(grid_tick ticks_gap, 0)
# Stops the grid by setting a config option that short-circuits the recursive
# requestAnimationFrame sequence in grid_tick
stop_grid = ->
grid_state.stopping = true
# Turns grid recording on
start_recording = ->
grid_state.recorder.start(1000)
# Turns grid recording off
stop_recording = ->
grid_state.stream.disconnect()
grid_state.recorder.stop()
# Event listeners for button which toggles grid recording
$record_grid.on "click", ->
if $record_grid.data("state") == "recording"
$record_grid.data("state", "stopped")
$record_grid.text "record"
stop_recording()
else
$record_grid.data("state", "recording")
$record_grid.text "record (stop)"
start_recording()
# Event listener to add a row to the grid
# Declares event listeners for the row (num cols, remove button)
$add_row.on "click", ->
$row_wrapper = build_row(grid_state.last_row_idx += 1)
$rows.append $row_wrapper
$ul = $row_wrapper.find "ul"
$num_cols = $row_wrapper.find ".num-cols"
$remove_row = $row_wrapper.find ".remove-row"
num_cols = ~~$default_row_length.val()
row_idx = grid_state.last_row_idx
set_num_cols(row_idx, num_cols, $rows, $row_wrapper, $ul)
$num_cols.val(num_cols)
grid_state.col_idxs[row_idx] = 0
reset_grid_state()
$remove_row.on "click", ->
grid_state.$containers.splice(row_idx, 1)
grid_state.col_idxs.splice row_idx, 1
state.grid_matrix.splice(row_idx, 1)
$row_wrapper.remove()
fix_containers_after_removal(row_idx)
$num_cols.on "input", (e) ->
$col = $(e.currentTarget)
row_idx = $ul.data("idx")
num_cols = ~~$num_cols.val()
$ul.empty()
set_num_cols row_idx, num_cols, $rows, $row_wrapper, $ul
# Button to toggle playback of the grid
$play_grid.on "click", ->
if $play_grid.data("state") == "playing"
$play_grid.text "play"
$play_grid.data("state", "stopped")
stop_grid()
else
$play_grid.text "stop"
$play_grid.data("state", "playing")
play_grid()
|
import React from 'react'
import useSpotify from '../hooks/useSpotify'
import { millisToMinutesAndSeconds } from '../lib/time'
import { useRecoilState } from 'recoil'
import { currentTrackIdState, isPlayingState} from '../atoms/songAtom'
const Song = ({track, order}) => {
const spotifyApi = useSpotify();
const {id, name, album, artists, duration_ms, uri } = track.track;
const [currentTrackId, setCurrentTrackId] = useRecoilState(currentTrackIdState);
const [isPlaying, setIsPlaying] = useRecoilState(isPlayingState);
const playSong = () => {
setCurrentTrackId(id);
setIsPlaying(true);
spotifyApi.play({
uris: [uri],
})
}
return (
<div className='grid grid-cols-2 text-gray-500 py-4 px-5
hover:bg-gray-900 rounded-full'
onClick={playSong}
>
<div className='flex items-center space-x-4'>
<p>{order + 1}</p>
<img
className='h-10 w-10'
src={album.images[0].url}
/>
<div>
<p className='w-36 lg:w-64 text-white truncate'>{name}</p>
<p className='w-40'>{artists[0].name}</p>
</div>
</div>
<div className='flex items-center
justify-between ml-auto md:ml-0'>
<p className='w-40 hidden md:inline'>{album.name}</p>
<p>{millisToMinutesAndSeconds(duration_ms)}</p>
</div>
</div>
)
}
export default Song
|
import { createSlice } from "@reduxjs/toolkit";
import { T_AppState } from "../../../../types";
const initialState: T_AppState = {
chatboxOpen: true,
};
export const appSlice = createSlice({
name: "app",
initialState,
reducers: {
toggleChatboxOpen: (state) => {
state.chatboxOpen = !state.chatboxOpen;
},
},
});
export const { toggleChatboxOpen } = appSlice.actions;
export default appSlice.reducer;
|
import { getCustomRepository } from "typeorm";
import { Authentication, AuthenticationModel } from "../domain/usecases/Authentication";
import { User } from "../models/Users";
import { Enctrypter } from "../protocols/Encrypter";
import { HashCompare } from "../protocols/HashCompare";
import { UserPostgresRepository } from "../repositories/UserPostgresRepository";
export class UserAuthentication implements Authentication {
private readonly encrypter: Enctrypter
private readonly hashCompare: HashCompare
constructor(encrypter: Enctrypter, hashCompare: HashCompare) {
this.encrypter = encrypter
this.hashCompare = hashCompare
}
async auth(authenticationModel: AuthenticationModel): Promise<string | null> {
const model = await this.makeRepo().findByEmail(authenticationModel.email)
if (model) {
const isValid = await this.hashCompare.compare(authenticationModel.password, model.password)
if (isValid) {
const accessToken = await this.encrypter.encrypt(model.id.toString())
return accessToken
}
}
return null
};
private makeRepo() {
return getCustomRepository(UserPostgresRepository)
}
}
|
import 'package:cowsandbulls/Services/auth.dart';
import 'package:flutter/material.dart';
class SignUp extends StatefulWidget {
final Function toggleView;
SignUp({required this.toggleView});
@override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String email = "";
String password = "";
String error = "";
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(25),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text("CowsNBulls",
style: TextStyle(
fontSize: 25, fontWeight: FontWeight.bold))
]),
const SizedBox(
height: 40,
),
Form(
key: _formKey,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
width: MediaQuery.of(context).size.width *
0.75,
height:
MediaQuery.of(context).size.height *
0.075,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey, width: 2),
borderRadius: const BorderRadius.all(
Radius.circular(5)),
color: Colors.white,
),
child: TextFormField(
validator: (val) => val!.isEmpty
? "Enter an email"
: null,
onChanged: (value) {
setState(() {
email = value;
});
},
decoration: const InputDecoration(
hintStyle: TextStyle(
fontSize: 15, color: Colors.grey),
border: InputBorder.none,
hintText: "gnani@email.com",
),
style: const TextStyle(
fontSize: 15, color: Colors.grey),
),
),
],
),
const SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
width:
MediaQuery.of(context).size.width *
0.75,
height:
MediaQuery.of(context).size.height *
0.075,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey, width: 2),
borderRadius:
const BorderRadius.all(
Radius.circular(5)),
color: Colors.white),
child: TextFormField(
validator: (val) => val!.length < 6
? "Enter a password of 6+ chars"
: null,
obscureText: true,
onChanged: (value) {
setState(() {
password = value;
});
},
style: const TextStyle(
fontSize: 15, color: Colors.grey),
cursorColor: const Color.fromARGB(
255, 253, 225, 75),
decoration: const InputDecoration(
hintStyle: TextStyle(
fontSize: 15,
color: Colors.grey),
border: InputBorder.none,
hintText: "*********",
),
))
],
),
const SizedBox(
height: 15,
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
width: MediaQuery.of(context).size.width *
0.75,
height:
MediaQuery.of(context).size.height *
0.18 /
3,
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.all(
Radius.circular(5))),
child: TextButton(
onPressed: () async {
//dynamic result = await _auth.SignUpAnon();
// if (result == null) {
// print("error SignUpg in");
// } else {
// print('Signed in');
// print(result.uid);
// }
if (_formKey.currentState!
.validate()) {
// print(email);
// print(password);
dynamic result = await _auth
.registerWithEmailAndPassword(
email, password);
if (result == null) {
setState(() {
error =
"Please enter a valid email";
});
}
}
},
child: const Text(
"Sign up",
style: TextStyle(
color: Colors.white,
fontSize: 15,
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(20),
width:
MediaQuery.of(context).size.width *
0.75,
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: const [
Text(
'OR',
style: TextStyle(
color: Colors.grey,
fontSize: 15),
),
],
))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
padding:
const EdgeInsets.only(bottom: 15),
width:
MediaQuery.of(context).size.width *
0.75,
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: const [
Text(
'Signup with Google',
style: TextStyle(
color: Colors.blue,
fontSize: 17),
),
],
))
],
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
width: MediaQuery.of(context).size.width *
0.75,
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
const Text("Have an account?",
style: TextStyle(
fontSize: 15,
color: Colors.grey)),
TextButton(
onPressed: () {
widget.toggleView();
},
child: const Text(
"Sign in",
style: TextStyle(
decoration: TextDecoration
.underline,
color: Colors.grey,
fontWeight: FontWeight.bold,
fontSize: 17),
))
],
),
)
],
),
],
),
]),
),
// Text(
// error,
// style: TextStyle(color: Colors.red, fontSize: 15),
// ),
]),
),
],
)
]),
));
}
}
|
<template>
<div :class="classForContainer">
<div v-if="isFullScreen" class="picker-hover">
<i class="fas fa-chevron-right"></i>
</div>
<div :class="classForPicker">
<el-collapse accordion>
<div>
<editor-header></editor-header>
<div class="cmp-picker-title">
<h5 @click="undo">Undo <i class="el-icon-refresh-left"></i></h5>
<h4>Drag from here</h4>
</div>
<el-collapse-item
v-for="type in types"
:title="type"
:key="'k' + type"
@click.native="loadThemes(type)"
>
<template v-if="themes">
<div class="collapse-items">
<ul class="collapse-items">
<Container
group-name="1"
:get-child-payload="getChildPayload1"
>
<Draggable
v-for="(theme, idx) in themes"
:key="idx * Date.now()"
>
<!-- {{
theme.type
}} -->
<li class="cmp-picker-options">
<img
:src="
require(`@/assets/cmp-picker-preview/` +
theme.imgPath)
"
/>
</li>
</Draggable>
</Container>
</ul>
</div>
</template>
</el-collapse-item>
</div>
<div class="wap-publish">
<!-- <el-button
class="save-btn"
@click="dialogFormVisible = true"
type="primary"
><span></span><i class="fas fa-save"></i
></el-button> -->
<a @click="copyUrl">Work together</a>
<div class="publish-icons">
<i @click="onMobileState('mobile')" class="el-icon-mobile"></i>
<i @click="onMobileState('desktop')" class="el-icon-monitor"></i>
</div>
<el-button @click="publishWap" type="primary"
><span>Publish</span><i class="el-icon-upload el-icon-right"></i
></el-button>
</div>
<!-- <el-dialog
title="Pick a name for your site"
:visible.sync="dialogFormVisible"
>
<el-form :model="form">
<el-form-item label="Site name" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">Cancel</el-button>
<el-button type="primary" @click="saveWap">Confirm</el-button>
</span>
</el-dialog> -->
</el-collapse>
</div>
</div>
</template>
<script>
import { Collapse, CollapseItem } from 'element-ui'
import wapHeader from '../wap-cmps/wap-header.cmp.vue'
import { cmpService } from '../../services/cmp.service.js'
import { Container, Draggable } from 'vue-smooth-dnd'
import editorHeader from '../editor-header.cmp.vue'
import { socketService } from '../../services/socket.service'
export default {
name: 'cmpPicker',
components: {
wapHeader,
Collapse,
CollapseItem,
Container,
Draggable,
editorHeader,
},
data() {
return {
themes: null,
types: [
'Headers',
'Galleries',
'Text',
'Contacts',
'Cards',
'Reviews',
'Landings',
'Footers',
],
wapToPublish: null,
isMobile: false,
dialogFormVisible: false,
form: {
name: '',
},
formLabelWidth: '100px',
isFullScreen: true,
}
},
watch: {
'$store.getters.isMobile'(isMobile) {
this.isMobile = isMobile
},
'$store.getters.isFullScreen'(isFullScreen) {
this.isFullScreen = isFullScreen
},
},
created() {
this.isFullScreen = this.$store.getters.isFullScreen
},
methods: {
copyUrl() {
const url = window.location.href
navigator.clipboard.writeText(url)
this.$notify({
group: 'foo',
title: 'URL Copied to Clipboard',
type: 'success',
text: 'Hello user! This is a notification!',
})
console.log(url)
},
undo() {
socketService.emit('wap undo', this.$store.getters.getCurrWap)
},
onMobileState(str) {
// console.log('HERE')
this.$store.dispatch({ type: 'setScreenState', str })
},
getChildPayload1(index) {
return this.themes[index]
},
publishWap() {
console.log('wapToPublish ID: ')
this.$notify({
group: 'foo',
title: 'Your website is now online!',
type: 'success',
text: 'Hello user! This is a notification!',
})
const wapCopy = JSON.parse(
// copy the json for creating new templates/sites
JSON.stringify(this.$store.getters.getCurrWap)
)
delete wapCopy._id
const JsonText = JSON.stringify(wapCopy)
// navigator.clipboard.writeText(JsonText);
console.log('copy to clip', JsonText)
window.open(`/publish/${this.$store.getters.getCurrWap._id}`, '_blank')
},
saveWap() {
//need to save to database the user waps
this.dialogFormVisible = false
const wapId = this.$store.getters.getCurrWap._id
const wapToSave = {
wapId,
siteName: this.form.name,
}
this.form.name = ''
const user = this.$store.getters.getUser
if (!user) this.$store.commit({ type: 'saveGuestWap', wapId: wapToSave })
//change it save in db guest waps
else {
user.waps.push(wapToSave)
this.$store.dispatch({ type: 'updateUser', user }) //user.waps.push(wapToSaveId);
}
console.log('saved', user)
},
async add(cmpId) {
// console.log(cmpId);
try {
const cmp = await this.$store.dispatch({
type: 'addCmp',
id: cmpId,
})
} catch (err) {
console.log(err)
}
},
loadThemes(cmpCat) {
const allThemes = cmpService.getThemesFor(cmpCat)
this.themes = allThemes
// console.log(this.themes);
},
getProperTxt(type) {
// console.log(type);
const textToShow = type.substring(4)
return textToShow.charAt(0).toUpperCase() + textToShow.slice(1)
},
},
computed: {
classForPicker() {
// const isFullScreen =
if (this.$store.getters.isFullScreen)
return 'cmp-picker-collapse scrollbar style-2 cmp-picker-fullscreen'
else return 'cmp-picker-collapse scrollbar style-2 cmp-picker'
},
classForContainer() {
if (this.$store.getters.isFullScreen)
return 'cmp-picker-container-fullscreen'
return 'cmp-picker-container'
},
},
}
</script>
<style></style>
|
import io
from os import path
from typing import Callable
from asyncio.queues import QueueEmpty
import os
import random
import re
import aiofiles
import aiohttp
import ffmpeg
import requests
from Process.fonts import CHAT_TITLE
from PIL import Image, ImageDraw, ImageFont
from Config import ASSISTANT_NAME, BOT_USERNAME, IMG_1, IMG_2, IMG_5
from Process.filters import command, other_filters
from Process.queues import QUEUE, add_to_queue
from ImageFont.main import call_py, user
from Process.utils import bash
from pyrogram import Client
from pyrogram.errors import UserAlreadyParticipant, UserNotParticipant
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from pytgcalls import StreamType
from pytgcalls.types.input_stream import AudioPiped
from youtubesearchpython import VideosSearch
import youtube_dl
def ytsearch(query: str):
try:
search = VideosSearch(query, limit=1).result()
data = search["result"][0]
songname = data["title"]
url = data["link"]
duration = data["duration"]
thumbnail = f"https://i.ytimg.com/vi/{data['id']}/hqdefault.jpg"
return [songname, url, duration, thumbnail]
except Exception as e:
print(e)
return 0
async def ytdl(format: str, link: str):
stdout, stderr = await bash(f'youtube-dl -g -f "{format}" {link}')
if stdout:
return 1, stdout.split("\n")[0]
return 0, stderr
chat_id = None
DISABLED_GROUPS = []
useer = "NaN"
ACTV_CALLS = []
def transcode(filename):
ffmpeg.input(filename).output(
"input.raw",
format="s16le",
acodec="pcm_s16le",
ac=2,
ar="48k"
).overwrite_output().run()
os.remove(filename)
def convert_seconds(seconds):
seconds = seconds % (24 * 3600)
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%02d:%02d" % (minutes, seconds)
def time_to_seconds(time):
stringt = str(time)
return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(":"))))
def changeImageSize(maxWidth, maxHeight, image):
widthRatio = maxWidth / image.size[0]
heightRatio = maxHeight / image.size[1]
newWidth = int(widthRatio * image.size[0])
newHeight = int(heightRatio * image.size[1])
newImage = image.resize((newWidth, newHeight))
return newImage
async def generate_cover(thumbnail, title, userid, ctitle):
async with aiohttp.ClientSession() as session:
async with session.get(thumbnail) as resp:
if resp.status == 200:
f = await aiofiles.open(f"thumb{userid}.png", mode="wb")
await f.write(await resp.read())
await f.close()
image1 = Image.open(f"thumb{userid}.png")
image2 = Image.open("ImageFont/raichux.png")
image3 = changeImageSize(1280, 720, image1)
image4 = changeImageSize(1280, 720, image2)
image5 = image3.convert("RGBA")
image6 = image4.convert("RGBA")
Image.alpha_composite(image5, image6).save(f"temp{userid}.png")
img = Image.open(f"temp{userid}.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("ImageFont/finalfont.ttf", 60)
font2 = ImageFont.truetype("ImageFont/finalfont.ttf", 70)
draw.text((20, 45), f"{title[:30]}...", fill= "white", stroke_width = 1, stroke_fill="white", font=font2)
draw.text((120, 595), f"Canlı müzik: {ctitle[:20]}...", fill="white", stroke_width = 1, stroke_fill="white" ,font=font)
img.save(f"final{userid}.png")
os.remove(f"temp{userid}.png")
os.remove(f"thumb{userid}.png")
final = f"final{userid}.png"
return final
@Client.on_message(command(["oynat", f"oynat@{BOT_USERNAME}", "play", f"play@{BOT_USERNAME}"]) & other_filters)
async def oynat(c: Client, m: Message):
await m.delete()
replied = m.reply_to_message
chat_id = m.chat.id
keyboard = InlineKeyboardMarkup(
[[
InlineKeyboardButton("⏹", callback_data="cbstop"),
InlineKeyboardButton("⏸", callback_data="cbpause"),
InlineKeyboardButton('⏭️', callback_data="skip"),
InlineKeyboardButton("▶️", callback_data="cbresume"),
],[
InlineKeyboardButton("📣 Kanal", url=f"https://t.me/Sohbetdestek"),
InlineKeyboardButton("🧩 Group", url=f"https://t.me/BotDestekGrubu"),
],[
InlineKeyboardButton("❌ Kapat", callback_data="cls")],
]
)
if m.sender_chat:
return await m.reply_text("you're an __Anonymous__ Admin !\n\n» yönetici haklarından kullanıcı hesabına geri dön.")
try:
aing = await c.get_me()
except Exception as e:
return await m.reply_text(f"error:\n\n{e}")
a = await c.get_chat_member(chat_id, aing.id)
if a.status != "administrator":
await m.reply_text(
f"💡 Beni kullanmak için, bir **Yönetici** aşağıdaki **izinler**:\n\n» ❌ __Delete messages__\n» ❌ __Add users__\n» ❌ __Manage video chat__\n\nVeri **Güncellenir** otomatik olarak sizden sonra **beni terfi ettir**"
)
return
if not a.can_manage_voice_chats:
await m.reply_text(
"missing required permission:" + "\n\n» ❌ __Manage video chat__"
)
return
if not a.can_delete_messages:
await m.reply_text(
"missing required permission:" + "\n\n» ❌ __Delete messages__"
)
return
if not a.can_invite_users:
await m.reply_text("missing required permission:" + "\n\n» ❌ __Add users__")
return
try:
ubot = (await user.get_me()).id
b = await c.get_chat_member(chat_id, ubot)
if b.status == "kicked":
await m.reply_text(
f"@{ASSISTANT_NAME} **yasaklanmış oturum** {m.chat.title}\n\n» **bu botu kullanmak istiyorsanız önce userbotun oturumunu açın.**"
)
return
except UserNotParticipant:
if m.chat.username:
try:
await user.join_chat(m.chat.username)
except Exception as e:
await m.reply_text(f"❌ **userbot katılamadı**\n\n**Sebep**: `{e}`")
return
else:
try:
invitelink = await c.export_chat_invite_link(
m.chat.id
)
if invitelink.startswith("https://t.me/+"):
invitelink = invitelink.replace(
"https://t.me/+", "https://t.me/joinchat/"
)
await user.join_chat(invitelink)
except UserAlreadyParticipant:
pass
except Exception as e:
return await m.reply_text(
f"❌ **userbot katılamadı**\n\n**Sebep**: `{e}`"
)
if replied:
if replied.audio or replied.voice:
suhu = await replied.reply("📥 **ses indiriliyor...**")
dl = await replied.download()
link = replied.link
if replied.audio:
if replied.audio.title:
songname = replied.audio.title[:70]
else:
if replied.audio.file_name:
songname = replied.audio.file_name[:70]
else:
songname = "Audio"
elif replied.voice:
songname = "Voice Note"
if chat_id in QUEUE:
pos = add_to_queue(chat_id, songname, dl, link, "Audio", 0)
await suhu.delete()
await m.reply_photo(
photo=f"{IMG_1}",
caption=f"💡 **Kuyruğa eklenen parça »** `{pos}`\n\n☑️ **Name:** [{songname}]({link}) | `music`\n💭 **Sohbet:** `{chat_id}`\n🎧 **Talep eden:** {m.from_user.mention()}",
reply_markup=keyboard,
)
else:
try:
await call_py.join_group_call(
chat_id,
AudioPiped(
dl,
),
stream_type=StreamType().local_stream,
)
add_to_queue(chat_id, songname, dl, link, "Audio", 0)
await suhu.delete()
requester = f"[{m.from_user.first_name}](tg://user?id={m.from_user.id})"
await m.reply_photo(
photo=f"{IMG_2}",
caption=f"☑️ **İsim:** [{songname}]({link})\n💭 **Sohbet:** `{chat_id}`\n💡 **Durum:** `Müzik çalıyor`\n🎧 **Talep eden:** {requester}\n📹 **Akış türü:** `Müzik`",
reply_markup=keyboard,
)
except Exception as e:
await suhu.delete()
await m.reply_text(f"🚫 error:\n\n» {e}")
else:
if len(m.command) < 2:
await m.reply_photo(
photo=f"{IMG_5}",
caption="💬**Usage: /play Müzik Çalmak için Bir Başlık Şarkısı Verin veya /vplay Video Oynatma için**"
,
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton("📣 Kanal", url=f"https://t.me/SohbetDestek"),
InlineKeyboardButton("🧩 Group", url=f"https://t.me/BOTDESTEKGRUBU")
],
[
InlineKeyboardButton("🗑 Kapat", callback_data="cls")
]
]
)
)
else:
suhu = await m.reply_text(
f"**Müzik İndiriyor**\n\n0% ▓▓▓▓▓▓▓▓▓▓▓▓ 100%"
)
query = m.text.split(None, 1)[1]
search = ytsearch(query)
if search == 0:
await suhu.edit("💬 **sonuç bulunamadı.**")
else:
songname = search[0]
title = search[0]
url = search[1]
duration = search[2]
thumbnail = search[3]
userid = m.from_user.id
gcname = m.chat.title
ctitle = await CHAT_TITLE(gcname)
image = await generate_cover(thumbnail, title, userid, ctitle)
format = "bestaudio[ext=m4a]"
abhi, ytlink = await ytdl(format, url)
if abhi == 0:
await suhu.edit(f"💬 yt-dl algılanan sorunlar\n\n» `{ytlink}`")
else:
if chat_id in QUEUE:
pos = add_to_queue(chat_id, songname, ytlink, url, "Audio", 0)
await suhu.delete()
requester = (
f"[{m.from_user.first_name}](tg://user?id={m.from_user.id})"
)
await m.reply_photo(
photo=image,
caption=f"💡 **Kuyruğa eklenen parça »** `{pos}`\n\n☑️ **Name:** [{songname[:22]}]({url}) | `Müzik`\n**⏱ Süre:** `{duration}`\n🎧 **Talep eden:** {requester}",
reply_markup=keyboard,
)
else:
try:
await suhu.edit("🔄 **Görüntülü sohbete katılma...**")
await call_py.join_group_call(
chat_id,
AudioPiped(
ytlink,
),
stream_type=StreamType().local_stream,
)
add_to_queue(chat_id, songname, ytlink, url, "Audio", 0)
await suhu.delete()
requester = f"[{m.from_user.first_name}](tg://user?id={m.from_user.id})"
await m.reply_photo(
photo=image,
caption=f"☑️ **İsim:** [{songname[:22]}]({url})\n**⏱ Süre:** `{duration}`\n💡 **Durum:** `Müzik çalıyor`\n🎧 **Talep eden:** {requester}",
reply_markup=keyboard,
)
except Exception as ep:
await suhu.delete()
await m.reply_text(f"💬 error: `{ep}`")
|
import React, { useState, useEffect } from "react";
import './index.css';
// API call for the list of towns/countries
const url = 'https://wft-geo-db.p.rapidapi.com/v1/geo/adminDivisions';
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY',
'X-RapidAPI-Host': 'wft-geo-db.p.rapidapi.com'
}
};
try {
const response = await fetch(url, options);
const result = await response.text();
console.log(result);
} catch (error) {
console.error(error);
}
// API call for the weather
const api = {
key: "3dd8ffa94db3f7bd6b6e9e7f1abb5f38",
base: "https://api.openweathermap.org/data/2.5/weather"
}
const weatherDescriptions = {
"Clear": "Dégagé",
"Clouds": "Nuageux",
"Rain": "Pluie",
"Thunderstorm": "Orageux",
"Mist": "Brouillard",
"Snow": "Neige"
};
function App() {
const [query, setQuery] = useState('');
const [weather, setWeather] = useState ({});
useEffect(() => {
if (typeof weather.weather !== "undefined") {
// Supprime toutes les classes de condition météorologique existantes
document.body.classList.remove("clouds", "rain", "thunderstorm", "clear", "mist", "snow");
// Ajoute la nouvelle classe basée sur la condition météorologique actuelle
document.body.classList.add(weather.weather[0].main.toLowerCase());
}
}, [weather]);
function search(evt) {
if (evt.key === "Enter") {
fetch(`${api.base}?q=${query.trim()}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('');
});
}
}
const dateBuilder = (d) => {
let months = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre",
"Octobre", "Novembre", "Décembre"];
let days = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"];
let day = days[d.getDay()];
let date = d.getDate();
let month = months[d.getMonth()];
let year = d.getFullYear();
return `${day} ${date} ${month} ${year}`
}
return (
<div className={`app ${(!weather.main || typeof weather.main === "undefined") ? 'base' : ''}`}>
<main>
<div className="search-box">
<input
type="text"
className="search-bar"
placeholder="Recherchez une ville ou un pays..."
onChange={e => setQuery(e.target.value)}
value={query}
onKeyPress={search}
/>
</div>
{(typeof weather.main != "undefined") ? (
<div>
<div className="location-box">
<div className="location">{weather.name}, {weather.sys.country}</div>
<div className="date">{dateBuilder(new Date())}</div>
</div>
<div className="weather-box">
<div className="temp">
{Math.round(weather.main.temp)}°c
</div>
<div className="weather">
{weatherDescriptions[weather.weather[0].main] || weather.weather[0].main}
</div>
</div>
</div>
) : ('')}
</main>
</div>
);
}
export default App;
|
/**
* @author T Motsoeneng
* @link https://github.com/themegat
*/
#include "TimeUtil.h"
#ifndef TEST_FLAG
#include <ArduinoLog.h>
#endif
long TimeUtil::getTimeBetween(String fromTime, String toTime)
{
long fT = toTimeStamp(fromTime);
long tT = toTimeStamp(toTime);
int secondsInDay = HOURS_IN_DAY * SECOND_IN_HOUR;
if (tT < fT)
{
tT = tT + secondsInDay;
}
long difference = tT - fT;
#ifndef TEST_FLAG
Log.info("TimeUtil::getTimeBetween fromTime: %s, toTime: %s, difference: %d" CR,
fromTime, toTime, difference);
#endif
return difference;
}
bool TimeUtil::isBetween(String fromTime, String toTime, String currentTime)
{
long fT = toTimeStamp(fromTime);
long tT = toTimeStamp(toTime);
long cT = toTimeStamp(currentTime);
int secondsInDay = HOURS_IN_DAY * SECOND_IN_HOUR;
if (cT < fT && cT < tT)
{
cT = cT + secondsInDay;
}
if (tT < fT)
{
tT = tT + secondsInDay;
}
return cT > fT && cT < tT;
}
long TimeUtil::toTimeStamp(String time)
{
String timeH = time.substring(0, time.indexOf(":"));
time.replace(timeH + ":", " ");
time.trim();
String timeM = time.substring(0, time.indexOf(":"));
time.replace(timeM + ":", " ");
time.trim();
int timeS = time.toInt();
long result = (timeH.toInt() * SECOND_IN_HOUR) + (timeM.toInt() * SECONDS) + timeS;
#ifndef TEST_FLAG
Log.info("TimeUtil::toTimeStamp result: %d" CR, result);
#endif
return result;
}
int TimeUtil::extractSeconds(long timeStamp)
{
long seconds = timeStamp / MILLISECONDS;
int result = seconds % SECONDS;
return result;
}
int TimeUtil::extractMinutes(long timeStamp)
{
long seconds = timeStamp / MILLISECONDS;
int result = (seconds % SECOND_IN_HOUR) / SECONDS;
return result;
}
int TimeUtil::extractHours(long timeStamp)
{
long seconds = timeStamp / MILLISECONDS;
int result = seconds / SECOND_IN_HOUR;
return result;
}
String TimeUtil::toTimeString(long timeStamp)
{
int hours = extractHours(timeStamp);
int minutes = extractMinutes(timeStamp);
int seconds = extractSeconds(timeStamp);
String result = String(hours) + ":" + String(minutes) + ":" + String(seconds);
return result;
}
|
import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "http";
import proxyEvents from "../cmd/events";
interface DisplayInterface {
url?: string,
statusCode?: number;
statusMessage?: string;
headers: IncomingHttpHeaders;
}
/**
* a class thad control sending information about requests and responses to console
*/
export default class ProxyDisplay {
private _logLevel: number;
private _req: DisplayInterface | undefined;
private _res: DisplayInterface | undefined;
constructor() {
this._logLevel = 1;
}
/**
* determines a level of information.
* @param {number} level - digit values between 0 and 3
*/
setLogLevel(level: number) {
this._logLevel = Number(level);
}
/**
* this method sending information about request to console
* @param req {DisplayInterface} - request from server
*/
displayRequest(req: DisplayInterface) {
this._req = req;
switch (this._logLevel) {
case 3:
this.to();
this.requestLine();
this.displayHeaders(this._req);
break;
case 2:
this.to();
this.requestLine();
break;
case 1:
this.to();
break;
default:
proxyEvents.emit('error', "unknown log level");
break;
}
}
/**
* this method sending information about response to console
* @param res {DisplayInterface} - response from http.request
*/
displayResponse(res: DisplayInterface) {
this._res = res;
if (this._res) {
switch (this._logLevel) {
case 1:
this.from();
break;
case 2:
this.from();
this.responseLine();
break;
case 3:
this.from();
this.responseLine();
this.displayHeaders(this._res);
break;
default:
proxyEvents.emit('error', "unknown log level");
break;
}
}
}
private to() {
console.log(`to: ${this._req?.headers['host']}`);
}
private from() {
console.log(`from: ${this._res?.headers['host']}`);
}
private requestLine() {
const rq = this._req as IncomingMessage;
const method = rq.method;
const http = rq.httpVersion;
const path = rq.url;
console.log(`${method} ${path} HTTP/${http}`);
}
private responseLine() {
const rs = this._res as IncomingMessage;
const http = rs.httpVersion;
const statusCode = rs.statusCode;
const statusMessage = rs.statusMessage;
console.log(`HTTP/${http} ${statusCode} ${statusMessage}`);
}
private displayHeaders(rqs: DisplayInterface) {
for (let header in rqs.headers) {
console.log(`${header}: ${rqs.headers[header]}`);
}
}
}
|
package com.xxmassdeveloper.mpchartexample.fragments;
import android.support.v4.app.Fragment;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.utils.FileUtils;
import java.util.ArrayList;
public abstract class SimpleFragment extends Fragment {
protected ChartData generateBarData(int dataSets, float range, int count) {
ArrayList<BarDataSet> sets = new ArrayList<BarDataSet>();
for(int i = 0; i < dataSets; i++) {
ArrayList<Entry> entries = new ArrayList<Entry>();
for(int j = 0; j < count; j++) {
entries.add(new Entry((float) (Math.random() * range) + range / 4, j));
}
BarDataSet ds = new BarDataSet(entries, getLabel(i));
sets.add(ds);
}
BarData d = new BarData(ChartData.generateXVals(0, count), sets);
return d;
}
protected ChartData generateScatterData(int dataSets, float range, int count) {
ArrayList<ScatterDataSet> sets = new ArrayList<ScatterDataSet>();
for(int i = 0; i < dataSets; i++) {
ArrayList<Entry> entries = new ArrayList<Entry>();
for(int j = 0; j < count; j++) {
entries.add(new Entry((float) (Math.random() * range) + range / 4, j));
}
ScatterDataSet ds = new ScatterDataSet(entries, getLabel(i));
sets.add(ds);
}
ScatterData d = new ScatterData(ChartData.generateXVals(0, count), sets);
return d;
}
/**
* generates less data (1 DataSet, 4 values)
* @return
*/
protected PieData generatePieData() {
int count = 4;
ArrayList<Entry> entries1 = new ArrayList<Entry>();
ArrayList<String> xVals = new ArrayList<String>();
xVals.add("Quarter 1");
xVals.add("Quarter 2");
xVals.add("Quarter 3");
xVals.add("Quarter 4");
for(int i = 0; i < count; i++) {
xVals.add("entry" + (i+1));
entries1.add(new Entry((float) (Math.random() * 60) + 40, i));
}
PieDataSet ds1 = new PieDataSet(entries1, "Quarterly Revenues 2014");
PieData d = new PieData(xVals, ds1);
return d;
}
protected LineData generateLineData() {
// DataSet ds1 = new DataSet(n, "O(n)");
// DataSet ds2 = new DataSet(nlogn, "O(nlogn)");
// DataSet ds3 = new DataSet(nsquare, "O(n\u00B2)");
// DataSet ds4 = new DataSet(nthree, "O(n\u00B3)");
ArrayList<LineDataSet> sets = new ArrayList<LineDataSet>();
// load DataSets from textfiles in assets folder
// sets.add(FileUtils.dataSetFromAssets(getActivity().getAssets(), "sine.txt"));
// sets.add(FileUtils.dataSetFromAssets(getActivity().getAssets(), "cosine.txt"));
// sets.add(FileUtils.dataSetFromAssets(getActivity().getAssets(), "n.txt"));
// sets.add(FileUtils.dataSetFromAssets(getActivity().getAssets(), "nlogn.txt"));
// sets.add(FileUtils.dataSetFromAssets(getActivity().getAssets(), "square.txt"));
// sets.add(FileUtils.dataSetFromAssets(getActivity().getAssets(), "three.txt"));
int max = Math.max(sets.get(0).getEntryCount(), sets.get(1).getEntryCount());
LineData d = new LineData(ChartData.generateXVals(0, max), sets);
return d;
}
private String[] mLabels = new String[] { "Company A", "Company B", "Company C", "Company D", "Company E", "Company F" };
// private String[] mXVals = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec" };
private String getLabel(int i) {
return mLabels[i];
}
}
|
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addDataDB, getDataDB, modifyDataDB, removeDataDB } from "./redux/modules/postSlice";
function App() {
const dispatch = useDispatch();
const postList = useSelector((state) => state.post.list);
const subjectRef = useRef();
const contentRef = useRef();
const onSubmit = (e) => {
e.preventDefault();
const data = {
subject: subjectRef.current.value,
content: contentRef.current.value
}
dispatch(addDataDB(data));
subjectRef.current.value = "";
contentRef.current.value = "";
}
const removePost = (id) => {
dispatch(removeDataDB(id));
}
const modifyPost = (id) => {
const data = {
subject: subjectRef.current.value,
content: contentRef.current.value
}
dispatch(modifyDataDB(id, data));
}
useEffect(() => {
dispatch(getDataDB());
}, []);
return (
<div>
{postList.map((v, index) => {
return (
<div key={index}>
<div>{v.subject}</div>
<div>{v.content}</div>
<button onClick={() => {modifyPost(v.id)}}>수정</button>
<button onClick={() => {removePost(v.id)}}>삭제</button>
</div>
)
})}
<form onSubmit={onSubmit}>
<input type="text" ref={subjectRef}/>
<input type="text" ref={contentRef}/>
<button>추가</button>
</form>
</div>
);
}
export default App;
|
import React from 'react';
import PropTypes from 'prop-types';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import GridContainer from '../../../../../components/GridContainer';
import GridItem from '../../../../../components/GridItem';
import UserOnlineStatus from './userOnlineStatus';
import { makeStyles } from '../../../../../components/material-ui';
import { getChatStreamId } from '../../../../../utils/stringAdditions';
import { selectCurrentUserAccount } from '../../../../../datastore/stormPathStore/selectors';
import { mapDispatchToProps } from '../../ChannelHeader';
import RenderAvatar from './renderAvatar';
const styles = () => ({
memberRowPadding: {
padding: 8,
},
noPadding: {
padding: 0,
},
});
const useStyles = makeStyles(styles);
function MemberLists(props) {
const classes = useStyles();
const userOnlineStatus = member => {
if (
member.id ===
getChatStreamId(props.currentUser.email, props.currentUser.id)
) {
return true;
}
return props.watchers && props.watchers.includes(member.id)
? member.online
: false;
};
const m = [];
Object.keys(props.members).forEach(function(k) {
m.push(props.members[k].user);
});
m.sort((a, b) => {
const nameA = a.name || '';
const nameB = b.name || '';
const aOnline = userOnlineStatus(a).toString();
const bOnline = userOnlineStatus(b).toString();
return (
aOnline.toString().localeCompare(bOnline) * -1 ||
nameA.localeCompare(nameB)
);
});
return (
<GridContainer direction="column" spacing={0}>
{m.map(u => (
<GridItem className={classes.memberRowPadding} key={u.id}>
<GridContainer>
<GridItem>{RenderAvatar(u.image, u.name)}</GridItem>
<GridItem>
<UserOnlineStatus
online={userOnlineStatus(u)}
templateId={props.templateId}
userId={u.id}
channelId={props.channelId}
/>
</GridItem>
</GridContainer>
</GridItem>
))}
</GridContainer>
);
}
MemberLists.propTypes = {
// hoc props
members: PropTypes.object,
watchers: PropTypes.array,
templateId: PropTypes.number,
channelId: PropTypes.string,
currentUser: PropTypes.object,
};
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUserAccount(),
});
export default compose(
connect(
mapStateToProps,
mapDispatchToProps,
),
)(React.memo(MemberLists));
|
import pytest
import base64
import json
import requests
from models import Role, Token
from config import host
import config
import time
URL = f"{config.scheme}://{config.host}"
def b64decode(s: str):
b = s.encode('utf-8')
return base64.decodebytes(b + b'=' * (-len(b) % 4))
def test_runtime_as_admin(admin_token: Token):
res = requests.get(f"{URL}/api/runtime", headers={"Authorization": admin_token.header()})
assert res.ok
info = res.json()
assert info["name"] == "Harry Brown"
assert "age" in info
assert "uptime" in info
assert "birthday" in info
assert "build" in info
assert "dependencies" in info
assert "module" in info
def test_runtime_as_user(user_token: Token):
res = requests.get(f"{URL}/api/runtime", headers={"Authorization": user_token.header()})
assert not res.ok
assert res.status_code >= 400 and res.status_code < 500
def test_token_revoke(admin_token: Token):
res = requests.post(
f"{URL}/api/revoke",
headers={"Authorization": admin_token.header()},
json={"refresh_token": admin_token.refresh_token}
)
assert res.ok
assert res.status_code == 200
res = requests.post(f"{URL}/api/refresh", json={
"refresh_token": admin_token.refresh_token,
})
assert not res.ok
assert res.status_code == 401
# Generating JWT tokens relies on the current time. So keep this last so that
# the session scoped token fixture is generated longer than a second before this
# test runs.
def test_token_refresh(user_token: Token):
# generating two JWT tokens in the same second will result in the same "iat"
# field and they will be the same.
time.sleep(1.0)
res = requests.post(f"{URL}/api/refresh", json={
"refresh_token": user_token.refresh_token,
})
assert res.ok
tok = Token(res.json())
assert tok.token != user_token.token
assert tok.expires > user_token.expires
assert tok.refresh_token == user_token.refresh_token
def test_token_claims_admin(admin_token: Token):
parts = admin_token.token.split(".")
assert len(parts) == 3
meta = json.loads(b64decode(parts[0]))
assert meta is not None
claims = json.loads(b64decode(parts[1]))
assert Role.ADMIN.value in claims["roles"]
assert claims['iss'] == 'harrybrwn.com'
assert claims['id'] != 0
assert len(claims['uuid']) > 0
def test_token_claims_user(user_token: Token):
parts = user_token.token.split(".")
assert len(parts) == 3
meta = json.loads(b64decode(parts[0]))
assert meta is not None
claims = json.loads(b64decode(parts[1]))
assert Role.DEFAULT.value in claims['roles']
assert claims['iss'] == 'harrybrwn.com'
assert claims['id'] != 0
assert len(claims['uuid']) > 0
def test_session():
ss = requests.Session()
res = ss.get("https://api.hrry.me-local/session")
assert res.ok
assert res.status_code == 200
key = ss.cookies["session"]
res = ss.get("https://api.hrry.me-local/session")
assert res.ok
assert res.cookies["session"] == key
assert res.cookies["session"] == ss.cookies["session"]
res = ss.get("https://api.hrry.me-local/api/health/ready")
assert res.ok
|
package frc.robot.utilities;
import java.util.ArrayList;
import edu.wpi.first.util.sendable.Sendable;
import edu.wpi.first.util.sendable.SendableBuilder;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class AlertSystem {
private AlertSystem() {}
private static ArrayList<Alert> errors = new ArrayList<>();
private static ArrayList<Alert> warnings = new ArrayList<>();
private static ArrayList<Alert> infos = new ArrayList<>();
public static void start() {
SmartDashboard.putData("Alerts", new Sendable() {
@Override
public void initSendable(SendableBuilder builder) {
builder.setSmartDashboardType("Alerts");
builder.addStringArrayProperty("errors", () -> getText(errors), null);
builder.addStringArrayProperty("warnings", () -> getText(warnings), null);
builder.addStringArrayProperty("infos", () -> getText(infos), null);
}
});
}
public static void addAlert(Alert alert) {
switch (alert.level) {
case Error:
errors.add(alert);
break;
case Warning:
warnings.add(alert);
break;
case Info:
infos.add(alert);
break;
}
}
public static void removeAlert(Alert alert) {
switch (alert.level) {
case Error:
errors.remove(alert);
break;
case Warning:
warnings.remove(alert);
break;
case Info:
infos.remove(alert);
break;
}
}
private static String[] getText(ArrayList<Alert> alerts) {
return alerts.stream()
.map(alert -> alert.text)
.toArray(String[]::new);
}
public static record Alert(String text, AlertLevel level) {};
public static enum AlertLevel {
Error, Warning, Info
}
}
|
import React, { useEffect, useState } from "react";
import MovieCard from "../components/MovieCard";
import { useDispatch, useSelector } from "react-redux";
import {
fetchMovieDataStart,
fetchMovieDataSuccess,
fetchMovieDataFailure,
} from "../redux/movie/movieSlice";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/scrollbar";
export default function Home() {
const dispatch = useDispatch();
const { allMovies, loading, error } = useSelector((state) => state.movie);
const { currentUser } = useSelector((state) => state.user);
// Local component state for filtering
const [movies, setMovies] = useState([]);
const [tvShows, setTvShows] = useState([]);
const [originals, setOriginals] = useState([]);
useEffect(() => {
try {
dispatch(fetchMovieDataStart());
const getMovies = async () => {
const res = await fetch("/api/movies");
const data = await res.json();
dispatch(fetchMovieDataSuccess(data));
};
getMovies();
} catch (error) {
dispatch(fetchMovieDataFailure(error));
}
}, []);
useEffect(() => {
// Filter movies on the client-side
const filteredMovies = allMovies.filter((movie) => movie.type === "Movie");
setMovies(filteredMovies);
const filteredTvShows = allMovies.filter(
(movie) => movie.type === "TvShow"
);
setTvShows(filteredTvShows);
const filteredOriginals = allMovies.filter(
(movie) => movie.type === "Originals"
);
setOriginals(filteredOriginals);
}, [allMovies]);
return (
<div className="max-w-[95%] mx-auto p-4">
{/* Top Picks */}
<div className="flex flex-col gap-1 my-2">
<h1 className="text-2xl font-semibold">
Top Picks For {currentUser.username.toUpperCase()}
</h1>
<div className="">
<Swiper
autoplay={{
delay: 2500,
disableOnInteraction: false,
}}
watchSlidesProgress={true}
slidesPerView={1}
modules={[Autoplay, Navigation]}
className="mySwiper"
spaceBetween={0}
breakpoints={{
640: {
slidesPerView: 4,
spaceBetween: 0,
},
768: {
slidesPerView: 3,
spaceBetween: 10,
},
1024: {
slidesPerView: 5,
spaceBetween: 10,
},
}}
>
{allMovies &&
allMovies.map((movie, index) => (
<SwiperSlide className="h-[180px]" key={index} style={{ margin: "0px" }}>
{error ? <p>Fetch error</p> : <MovieCard movie={movie} />}
</SwiperSlide>
))}
</Swiper>
</div>
</div>
{/* Latest Movies */}
<div className="flex flex-col gap-1 my-2">
<h1 className="text-2xl font-semibold">Latest Movies</h1>
<div className="">
<Swiper
watchSlidesProgress={true}
slidesPerView={1}
modules={[Navigation]}
className="mySwiper"
spaceBetween={0}
breakpoints={{
640: {
slidesPerView: 4,
spaceBetween: 0,
},
768: {
slidesPerView: 3,
spaceBetween: 10,
},
1024: {
slidesPerView: 5,
spaceBetween: 10,
},
}}
>
{movies.map((movie, index) => (
<SwiperSlide className="h-[180px]" key={index} style={{ margin: "0px" }}>
{error ? (
<p>Fetch error</p>
) : (
<MovieCard movie={movie} loading={loading} />
)}
</SwiperSlide>
))}
</Swiper>
</div>
</div>
{/* Latest Tv Shows */}
<div className="flex flex-col gap-1 my-2">
<h1 className="text-2xl font-semibold">Latest Tv Shows</h1>
<div className="">
<Swiper
watchSlidesProgress={true}
slidesPerView={1}
modules={[Navigation]}
className="mySwiper"
spaceBetween={0}
breakpoints={{
640: {
slidesPerView: 4,
spaceBetween: 0,
},
768: {
slidesPerView: 3,
spaceBetween: 10,
},
1024: {
slidesPerView: 5,
spaceBetween: 10,
},
}}
>
{tvShows.map((movie, index) => (
<SwiperSlide className="h-[180px]" key={index} style={{ margin: "0px" }}>
{error ? (
<p>Fetch error</p>
) : (
<MovieCard movie={movie} loading={loading} />
)}
</SwiperSlide>
))}
</Swiper>
</div>
</div>
{/* Latest Originals */}
<div className="flex flex-col gap-1 my-2">
<h1 className="text-2xl font-semibold">Latest Originals</h1>
<div className="">
<Swiper
watchSlidesProgress={true}
slidesPerView={1}
modules={[Navigation]}
className="mySwiper"
spaceBetween={0}
breakpoints={{
640: {
slidesPerView: 4,
spaceBetween: 0,
},
768: {
slidesPerView: 3,
spaceBetween: 10,
},
1024: {
slidesPerView: 5,
spaceBetween: 10,
},
}}
>
{originals.map((movie, index) => (
<SwiperSlide className="h-[180px]" key={index} style={{ margin: "0px" }}>
{error ? (
<p>Fetch error</p>
) : (
<MovieCard movie={movie} loading={loading} />
)}
</SwiperSlide>
))}
</Swiper>
</div>
</div>
</div>
);
}
|
%
% rtn2eci_matrix Rotation matrix from Hill/orbital (RTN) frame to Earth-
% centered inertial (ECI) frame.
%
% R_rtn2eci = rtn2eci_matrix(r_eci,v_eci)
%
% See also eci2rtn_matrix.
%
% Author: Tamas Kis
% Last Update: 2022-02-16
%
% REFERENCES:
% [1] Vallado, "Fundamentals of Astrodynamics and Applications", 4th Ed.
% (pp. 163-164)
%
%--------------------------------------------------------------------------
%
% ------
% INPUT:
% ------
% r_eci - (3×1 double) position resolved in ECI frame
% v_eci - (3×1 double) inertial velocity resolved in ECI frame
%
% -------
% OUTPUT:
% -------
% R_rtn2eci - (3×3 double) rotation matrix (RTN --> ECI)
%
% -----
% NOTE:
% -----
% --> r_eci and v_eci can be input in any units, but they MUST be
% consistent.
%
function R_rtn2eci = rtn2eci_matrix(r,v)
% R, T, and N basis vectors resolved in ECI frame
R_eci = r/inorm(r);
N_eci = cross(r,v)/inorm(cross(r,v));
T_eci = cross(N_eci,R_eci);
% rotation matrix from RTN frame to ECI frame
R_rtn2eci = [R_eci,T_eci,N_eci];
end
|
import React, { useEffect, useState } from 'react'
import { View, StyleSheet, StyleProp, ViewStyle } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
import Icon from 'react-native-vector-icons/Ionicons';
import { useDebounce } from '../hooks/useDebounce';
interface Props{
onDebaunce: (value: string) => void;
style?: StyleProp<ViewStyle>;
}
export const SearchInput = ({style, onDebaunce}: Props) => {
const [inputValue, setInputValue] = useState('');
const debounceValue = useDebounce(inputValue, 500);
useEffect(() => {
onDebaunce(debounceValue);
}, [debounceValue])
return (
<View style={{
...styles.container,
...style as any
}}>
<View style={styles.textBackgorund}>
<TextInput
placeholder='search pokemon'
placeholderTextColor='grey'
style={styles.textInput}
autoCapitalize='none'
autoCorrect={false}
value={inputValue}
onChangeText={setInputValue}
/>
<Icon name='search-outline' color='grey' size={25}/>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
marginHorizontal: 20
},
textBackgorund: {
backgroundColor:'#F3F1F3',
borderRadius: 50,
color: 'grey',
height: 50,
paddingHorizontal: 20,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 3,
},
shadowOpacity: 0.29,
shadowRadius: 4.65,
elevation: 7,
},
textInput:{
flex: 1,
fontSize: 18,
color: '#000'
}
});
|
<template>
<Page>
<AppMenu @onOpenDrawer="onOpenMenu" @onCloseDrawer="onCloseMenu"/>
<ActionBar>
<DockLayout>
<Label text="metaspan" dock="left" />
<Label :text="chain" dock="center" />
<ActivityIndicator :busy="loading" @busyChange="onBusyChanged" />
<Button @tap="onOpenDrawer('right')" text="Menu" width="50" dock="right" />
</DockLayout>
</ActionBar>
<Drawer ref="drawer">
<!-- <GridLayout ~leftDrawer class="drawer" width="65%" height="100%" backgroundColor="white" padding="25">
<Label text="Left Drawer" verticalAlignment="top" />
</GridLayout> -->
<GridLayout ~rightDrawer class="drawer" width="65%" height="100%" backgroundColor="white" padding="25">
<Label text="Right Drawer" verticalAlignment="top" />
<!-- <a href="myapp://views/navigate.html">Open App</a> -->
<Button @tap="openApp()" text="Open App" width="50" dock="right" />
</GridLayout>
<!-- <GridLayout ~topDrawer class="drawer" height="65%" width="100%" backgroundColor="white" padding="25">
<Label text="Top Drawer" verticalAlignment="top" />
</GridLayout> -->
<!-- <GridLayout ~bottomDrawer class="drawer" height="65%" width="100%" backgroundColor="white" padding="25">
<Label text="Bottom Drawer" verticalAlignment="top" />
</GridLayout> -->
<!-- <StackLayout ~mainContent backgroundColor="white">
<Button @tap="onOpenDrawer('left')" text="Open Left Drawer" width="250" marginTop="25" />
<Button @tap="onOpenDrawer('right')" text="Open Right Drawer" width="250" marginTop="25" />
<Button @tap="onOpenDrawer('top')" text="Open Top Drawer" width="250" marginTop="25" />
<Button @tap="onOpenDrawer('bottom')" text="Open Bottom Drawer" width="250" marginTop="25" />
</StackLayout> -->
<PullToRefresh ~mainContent @refresh="onPullToRefresh">
<Placeholder @creatingView="creatingView" />
<ListView
height="100%"
for="item in list"
@itemTap="onTap">
<v-template>
<GridLayout
height="40"
borderRadius="10"
class="bg-secondary"
rows="*, auto, auto"
columns="*"
margin="5 10"
padding="0"
>
<!-- <image row="0" margin="0" stretch="aspectFill" :src="item.image" /> -->
<Label
row="1"
margin="10 10 0 10"
fontWeight="700"
class="text-primary"
fontSize="18"
:text="item.name"
/>
<Label
row="2"
margin="0 10 10 10"
class="text-secondary"
fontSize="14"
textWrap="true"
:text="item.stash"
/>
</GridLayout>
</v-template>
</ListView>
</PullToRefresh>
</Drawer>
</Page>
</template>
<script lang="ts">
import Vue from "nativescript-vue";
import { mapState } from 'vuex'
import { availableSync } from '@nativescript/appavailability'
import { Utils } from '@nativescript/core'
// import { EventData } from "tns-core-modules/data/observable";
import AppMenu from "./AppMenu.vue";
import { CandidateModel } from '../models/Candidate'
// import CandidateService from '../services/CandidateService'
// import Details from './Details.vue'
import Candidate from './Candidate.vue'
// import Label from 'nativescript-vue'
// const flickService = new FlickService()
// const candidateService = new CandidateService('kusama')
interface IData {
refreshing: boolean
}
interface IMethods {
// onPageLoaded(event: EventData): void
creatingView(args: any): void
onPullToRefresh(args: any): void
onTap(args: any): void
onBusyChanged(event: any): void
onOpenDrawer(side: string): void
onOpenMenu(event: any): void
onCloseMenu(event: any): void
openApp(): void
}
interface IComputed {
loading: boolean
message: string
chain: string
list: CandidateModel[]
}
interface IProps {}
export default Vue.extend<IData, IMethods, IComputed, IProps>({
components: {
AppMenu
},
computed: {
message() {
return "Blank {N}-Vue app";
},
...mapState(['chain']),
...mapState('candidate', ['loading', 'list'])
},
data () {
return {
refreshing: false,
// flicks: flickService.getFlicks(),
// candidates: [] as CandidateModel[]
}
},
methods: {
// async onPageLoaded(event: EventData) {
// console.log('onPageLoaded()', event)
// },
creatingView: function(args: any) {
// const nativeView = new Label();
// nativeView.text = "Native View - iOS";
args.view = 'nativeView';
},
async onPullToRefresh (args: any) {
console.log('onPullToRefresh()...')
// this.candidates = await candidateService.getCandidates()
await this.$store.dispatch('candidate/setList')
var pullRefresh = args.object;
setTimeout(function() {
pullRefresh.refreshing = false;
}, 1000);
},
onTap (args: any) {
const stash = args.item.stash
this.$navigateTo(Candidate, {
props: { chain: this.chain, stash }
})
},
onBusyChanged (event) {
console.log('onBusyChanged', event)
},
onOpenDrawer (side: string) {
(this.$refs['drawer'] as any)?.open(side);
},
onOpenMenu (event: any) {
// console.log('onOpenMenu', event)
},
onCloseMenu (event: any) {
// console.log('onCloseMenu', event)
},
async openApp () {
// <a href="myapp://views/navigate.html"
console.log('openApp() firing... myapp')
// await Utils.openUrl('metaspan://kusama/hello=world&one=2')
// console.log('openApp() done...')
// if (availableSync('myapp')) {
// console.log('will try to open myapp')
Utils.openUrl(
'myapp://user?user_id=eddyverbruggen'
)
// } else {
// console.log('falling back to website')
// Utils.openUrl('https://metaspan.com/#metapay')
// }
}
},
async mounted () {
console.log('Home.vue mounted...')
// await candidateService.init()
// this.candidates = await candidateService.getCandidates()
}
})
</script>
<style scoped lang="scss">
@import '@nativescript/theme/scss/variables/blue';
// Custom styles
.fas {
@include colorize($color: accent);
}
.info {
font-size: 20;
horizontal-align: center;
vertical-align: center;
}
.mdi {
font-family: "Material Design Icons", "materialdesignicons-webfont";
}
</style>
|
<template>
<div class="production-container">
<el-table
:data="tableData"
style="width: 100%"
:header-cell-style="headerCellStyle"
:cell-style="{ textAlign: 'center' }"
max-height="440"
>
<el-table-column type="index" label="序号" width="80" />
<el-table-column label="图片">
<template #default="scope">
<el-image
:src="scope.row.img1"
preview-teleported
:preview-src-list="[
scope.row.img1,
scope.row.img2,
scope.row.img3,
scope.row.img4
]"
></el-image>
</template>
</el-table-column>
<el-table-column prop="proname" label="名称"></el-table-column>
<el-table-column prop="brand" label="品牌"></el-table-column>
<el-table-column
prop="category"
:filters="filters"
:filter-method="filterHandler"
label="分类"
></el-table-column>
<el-table-column
prop="originprice"
sortable
label="原价"
></el-table-column>
<el-table-column prop="discount" sortable label="折扣"></el-table-column>
<el-table-column prop="sales" sortable label="销量"></el-table-column>
<el-table-column prop="issale" label="是否售卖">
<template #default="scope">
<el-switch
v-model="scope.row.issale"
:active-value="1"
:inactive-value="0"
:disabled="disabled"
@change="changeSwitch(scope.row.proid, 'issale', scope.row.issale)"
/>
</template>
</el-table-column>
<el-table-column prop="isseckill" label="是否秒杀">
<template #default="scope">
<el-switch
v-model="scope.row.isseckill"
:active-value="1"
:inactive-value="0"
:disabled="disabled"
@change="
changeSwitch(scope.row.proid, 'isseckill', scope.row.isseckill)
"
/>
</template>
</el-table-column>
<el-table-column prop="isrecommend" label="是否推荐">
<template #default="scope">
<el-switch
v-model="scope.row.isrecommend"
:active-value="1"
:inactive-value="0"
:disabled="disabled"
@change="
changeSwitch(
scope.row.proid,
'isrecommend',
scope.row.isrecommend
)
"
/>
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-popconfirm
title="确认要删除吗?"
@confirm="handleDelete(scope.row.proid)"
>
<template #reference>
<el-button size="small" type="danger">删除</el-button>
</template>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!-- 分页器 -->
<el-pagination
background
layout="total,prev, pager, next"
:total="total"
v-model:current-page="currentPage"
v-model:page-size="pageSize"
@current-change="changeCurrent"
/>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import { getProList, updateProductionFlag } from '@/api/production'
export default defineComponent({
data() {
return {
total: 1,
value1: true,
currentPage: 1,
disabled: false,
pageSize: 10,
tableData: [],
headerCellStyle: {
color: 'rgba(0,0,0,0.85)',
fontWeight: '700',
fontSize: '14px',
textAlign: 'center',
background: '#f8f8f8',
height: '60px',
borderRight: '1px solid #f0f0f0',
transition: 'background .3s ease'
}
}
},
computed: {
filters() {
let arr = this.tableData.map((item) => item.category)
arr = [...new Set(arr)]
return arr.map((item) => {
return {
text: item,
value: item
}
})
}
},
methods: {
handleDelete(proid) {
console.log(proid)
},
filterHandler(value, row, column) {
const property = column['property']
return row[property] === value
},
getProListData() {
getProList({
count: this.currentPage,
limitNum: this.pageSize
}).then((res) => {
console.log(res)
this.tableData = res.data
this.total = res.total
})
},
changeCurrent() {
this.getProListData()
},
changeSwitch(proid, type, flag) {
this.disabled = true
updateProductionFlag({
proid,
type,
flag: !!flag
}).then(() => {
this.getProListData()
this.disabled = false
})
}
},
created() {
this.getProListData()
}
})
</script>
<style lang="scss" scoped>
.production-container {
height: 100%;
padding: 24px;
background: #fff;
}
.el-pagination {
display: flex;
justify-content: flex-end;
margin-top: 24px;
}
</style>
|
"use client";
import { Button } from "@/components/ui/button";
import {
FormField,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/components/ui/use-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { Prisma, Project } from "@prisma/client";
import axios from "axios";
import { useSession } from "next-auth/react";
import { FormProvider, useFieldArray, useForm } from "react-hook-form";
import * as z from "zod";
const formSchema = z.object({
title: z.string(),
description: z.string().optional(),
statuses: z.object({ name: z.string() }).array().optional(),
});
type Props = {
onCreated: (project: Project) => void;
};
export function CreateProjectForm({ onCreated }: Props) {
const { toast } = useToast();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
title: "",
description: "",
statuses: [],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "statuses",
});
const handleStatusBlur = (
e: React.FocusEvent<HTMLInputElement>,
index: number
) => {
const value = e.target.value;
if (!value) {
//cleanup empty values
remove(index);
}
};
const handleAddStatus = () => {
append({ name: "" });
};
function onSubmit(values: z.infer<typeof formSchema>) {
axios
.post<Project>("/api/secured/projects", {
...values,
})
.then((res) => {
onCreated(res.data);
});
}
return (
<FormProvider {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<Input placeholder="Meaningful text" {...field} />
</FormControl>
<FormDescription>
title is required, but you can edit it later
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea {...field} />
</FormControl>
<FormDescription>description is optional</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<hr className="border-none h-px bg-slate-400/50" />
<div>
<FormLabel>Statuses</FormLabel>
<div className="mt-2 flex flex-col gap-2">
{fields.map((field, index) => (
<FormField
key={field.id} // Ensure each field has a unique key
control={form.control}
name="statuses"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
className="max-w-[200px]"
placeholder="Status name"
type="text"
{...form.register(`statuses.${index}.name` as const)}
onBlur={(e) => handleStatusBlur(e, index)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
))}
</div>
<FormDescription className="mt-2">
Statuses are optional, you can create them later
</FormDescription>
<Button
type="button"
onClick={handleAddStatus}
className="mt-2"
size="sm"
variant="outline"
>
Add status
</Button>
</div>
<hr className="border-none h-px bg-slate-400/50" />
<Button type="submit">Create</Button>
</form>
</FormProvider>
);
}
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pgproject/exchange/bloc/exchange_bloc.dart';
import 'package:pgproject/exchange/ui/widgets/currency_selection_dropdown.dart';
import 'package:pgproject/exchange/ui/widgets/currency_value_input_area.dart';
import 'package:pgproject/exchange/utility/exchange_style_constants.dart';
class ExchangePage extends StatefulWidget {
const ExchangePage({super.key});
@override
State<ExchangePage> createState() => _ExchangePageState();
}
class _ExchangePageState extends State<ExchangePage> {
final String appbarTitle = "KUR ÇEVİRME";
final String paraBirimi = "PARA BİRİMİ";
final String miktar = "MİKTAR";
final ExchangeBloc bloc = ExchangeBloc();
@override
void initState() {
super.initState();
bloc.add(ExchangeFetchListEvent());
}
@override
void dispose() {
super.dispose();
bloc.close();
}
@override
Widget build(BuildContext context) {
return PopScope(
onPopInvoked: (didPop) {
bloc.add(ExchangeBackButtonClickEvent());
},
child: Scaffold(
appBar: AppBar(
title: Text(appbarTitle),
centerTitle: true,
backgroundColor: Colors.blueAccent,
),
body: Center(
child: BlocBuilder<ExchangeBloc, ExchangeState>(
buildWhen: (previous, current) => current is! ExchangeActionState,
bloc: bloc,
builder: (context, state) {
if (state is ExchangeFetchListState) {
return const CircularProgressIndicator();
} else if (state is ExchangeInitialState) {
return _main(state);
}
return Container();
},
),
),
),
);
}
Widget _main(ExchangeInitialState state) {
return Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: ExchangeStyleConstants.heightSpace20,
),
Text(
paraBirimi,
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(
height: ExchangeStyleConstants.heightSpace20,
),
CurrencySelectionDropdown(bloc: bloc, state: state),
const SizedBox(
height: ExchangeStyleConstants.heightSpace20,
),
Text(
miktar,
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(
height: ExchangeStyleConstants.heightSpace20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
CurrencyValueInputArea(
state: state,
bloc: bloc,
),
const SizedBox(width: 30),
_totalResult(state),
],
),
],
),
);
}
Widget _totalResult(ExchangeInitialState state) {
return Container(
padding: const EdgeInsets.all(15),
color: Colors.grey,
child: Text(state.result.toStringAsFixed(2)),
);
}
}
|
let productQuantityControls = document.querySelectorAll('.product__quantity-control');
let addToCartButtons = document.querySelectorAll('.product__add');
for (let control of productQuantityControls) {
control.addEventListener('click', function () {
let product = control.closest('.product');
let productCount = product.querySelector('.product__quantity-value');
let value = productCount.textContent;
if (control.classList.contains('product__quantity-control_inc')) {
value++;
} else if (control.classList.contains('product__quantity-control_dec')) {
value--;
if (value < 1) {
value = 1;
}
}
productCount.textContent = value;
});
}
for (let addButton of addToCartButtons) {
addButton.addEventListener('click', function () {
let product = addButton.closest('.product');
let productId = product.dataset.id;
let img = product.querySelector('.product__image');
let productImg = img.getAttribute('src');
let productCount = product.querySelector('.product__quantity-value');
let value = Number(productCount.textContent);
let cartProduct = null;
let products = document.querySelectorAll('.cart__product');
for (let oneProduct of products) {
if (oneProduct.dataset.id == productId) {
cartProduct = oneProduct;
}
}
if (cartProduct){
let cartProductCount = cartProduct.querySelector('.cart__product-count');
let cartProductValue = Number(cartProductCount.textContent);
cartProductCount.textContent = cartProductValue + value;
} else {
let cartProducts = document.querySelector('.cart__products');
let newCartProduct = document.createElement('div');
newCartProduct.className = 'cart__product';
newCartProduct.dataset.id = productId;
let newCartProductImg = document.createElement('img');
newCartProductImg.classList.add('cart__product-image');
newCartProductImg.src = productImg;
newCartProduct.appendChild(newCartProductImg);
let newCartProductCount = document.createElement('div');
newCartProductCount.className = 'cart__product-count';
newCartProductCount.textContent = value;
newCartProduct.appendChild(newCartProductCount);
cartProducts.appendChild(newCartProduct);
}
});
}
|
---
id: gcae
title: Google Cloud App Engine
description: Google Cloud App Engine
tags:
- Google Cloud App Engine
- PHP
---
## Custom Docker
To install the PHP monitoring agent in the Google Cloud App engine, the custom docker must be used.
**Defaults of Google App Engine PHP cannot run PHP extension modules and service daemons**. Install them via Docker Container.
In the _app.yaml_ file (Google App engine's configuration file), configure the settings with the `flex` environment and `custom` run-time.
```yaml title=SH
$ vi app.yaml
env: flex
runtime: custom
```
To run with the custom Docker, create _Dockerfile_ in the same location as _app.yaml_ set with the `flex` environment and the `custom` run-time. See the default PHP Docker image for the Google App engine.
```docker title=Docker
# google-appengine php php56, php70, php71
FROM gcr.io/google-appengine/php56
```
## Installation of the PHP monitoring agent
Install the PHP monitoring agent.
1. Install the library (wget).
```docker
RUN apt-get install wget -y
```
2. Create the php-fpm execution command link.
```docker
RUN ln -s /opt/php/sbin/php-fpm /usr/bin/php-fpm
```
3. Install the WhaTap repository and whatap-php package.
```docker
RUN wget http://repo.whatap.io/debian/release.gpg -O -| apt-key add -
RUN wget http://repo.whatap.io/debian/whatap-repo_1.0_all.deb
RUN dpkg -i whatap-repo_1.0_all.deb
RUN apt-get update
RUN apt-get install whatap-php
```
4. Configure the PHP extension module and whatap-php service.
```docker
#RUN (echo "[granted access key]"; echo "[granted server IP ]")|/usr/whatap/php/install.sh
RUN (echo "xxxxxxxx"; echo "1.1.1.1/2.2.2.2")|/usr/whatap/php/install.sh
```
:::note
After creating a PHP monitoring project, the **access key** and server IP is issued. With the delimiter (_/_), multiple IPs can be issued.
:::
5. Run the whatap-php service through `supervisor`.
```docker
RUN echo "[program:whatap-php]" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "command = /etc/init.d/whatap-php start" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "stdout_logfile = /dev/stdout" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "stdout_logfile_maxbytes=0" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "stderr_logfile = /dev/stderr" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "stderr_logfile_maxbytes=0" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "user = root" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "autostart = true" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "autorestart = true" >> /etc/supervisor/conf.d/whatap.conf
RUN echo "priority = 10" >> /etc/supervisor/conf.d/whatap.conf
```
## Adding firewall rules
Add firewall rules for the network that is used by the Google App engine. TCP transmission must be allowed through the port 6600 for the issued server IP.
## Checking the deployment and instance
Deploy _app.yaml_ and _Dockerfile_ that have been set through the Google Cloud SDK.
```bash title=SH
$ gcloud app deploy
```
Check the App engine instance generated in the Google Cloud Console.
<!--
방화벽 규칙 추가


앱 엔진 생성 인스턴스 확인

-->
|
% -*- mode: LaTex; outline-regexp: "\\\\section\\|\\\\subsection";fill-column: 80; -*-
\documentclass[12pt]{article}
\usepackage[longnamesfirst]{natbib}
\usepackage[usenames]{color}
\usepackage{amssymb}
\usepackage{graphicx}
\input{/Users/bob/work/papers/standard}
\newtheorem{assumption}{Assumption}
% --- Paragraph split
\setlength{\parskip}{0.00in}
% --- Line spacing
\renewcommand{\baselinestretch}{1.4}
% --- Hypthenation
\sloppy % fewer hyphenated
\hyphenation{stan-dard}
\hyphenation{among}
% --- Customized commands, abbreviations
\newcommand{\TIT}{{\it {\small Implementing the Auction}}}
\newcommand{\eps}{\epsilon}
% --- Header
\pagestyle{myheadings}
\markright{\TIT}
% --- Title
\title{
Implementing the Auction
}
\author{
Robert A. Stine \\
Department of Statistics \\
The Wharton School of the University of Pennsylvania \\
Philadelphia, PA 19104-6340 \\
}
\date{\today}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\maketitle
\vspace{-0.5in} \centerline{\bf Abstract}
\clearpage
\section*{Reading and handling data} % ----------------------------------------
The first step of data processing is to convert everything into numbers. The
code that runs the auction only accommodates numerical variables. Everything
-- missing data, categorical variables -- must be represented numerically. The
program {\tt csv\_parser} handles this chore. (The file {\tt csv\_parser.cc}
is kept in the {\tt boost} directory.) This command line tool converts data
given in a csv file into the format used in the auction. The most useful
application of {\tt csv\_parser} puts files representing the variables into a
named directory along with a shell script {\tt index.sh} for writing the data
in streaming style.
\subsection*{Parsing a csv file}
The first line of the input CSV file holds the names of the variables and any
descriptive information, basically the sort of named columns used by JMP or R.
Names can consist of characters, numbers, spaces and the characters:
\begin{verbatim}
. _ [ ] /
\end{verbatim}
Others might ought to be added the in later parsing of variables. If the same
name is used for two (or more columns), the second occurance will have ``\_2''
appended, then ``\_3'', and so forth.
The first column in the CSV file identifies an indicator for cross-validation.
If the first input column is a list of the labels ``in'' and ``out'', then
this variable will be flagged as indicating which cases to use in the model,
and which to reserve for validation. Rather than generate 2 indicators (one
for every symbol as done for explantory categorical variables), this step will
only generate 1. This indicator will be placed in a file called {\tt
context.dat} to be distinguished from the response and from the explanatory
variables. In the auction, only those cases marked "in" will be used for
estimation. All cases will be predicted.
In addition to supplying names, the first line of the CSV file also assigns
attributes to variables. This is done by listing name=value pairs of
attributes within curly brackets and separated by semi-colons. No spaces are
allowed within the attributes. For example, the first line of the file might
look like this:
\begin{verbatim}
Variable_x {role=x;stream=eigen1;type=real}
\end{verbatim}
Currently used attributes defined by the software are
\begin{tabular}{cl}
role & One of ``x'', ``y'' or ``context'' (defaults to x). \cr
stream & Identifies a specific input stream (defaults to main). \cr
\end{tabular}
\noindent
You must make one variable the response, or the software won't know which to
use. The default stream option is for convenience since it avoids having to
use the bracketed option {stream=main} for every variable in the file.
As an example, an input csv file with 3 variables might begin as follows
\begin{verbatim}
cv, Y, Var1, a/b, Var.3{stream=sub;priority=2;knots=4}
out, 2, 1, 2, 3
in, 6, 3, 4, 5
in, 3, a, , 5
\end{verbatim}
The presence of a non-numerical symbol (in the example, the 'a' in the 3rd row)
in the data for Var1 converts Var1 into a categorical variable. Every unique
value found in this column will cause the software to generate an indicator
(so, you'll get a lot of these if this was an accident and the column really is
numerical). Blanks indicate missing values, as shown on the last line of the
prior example. {\tt csv\_parser} automatically builds an indicator for any
variable that has missing data and fills the missing values with the mean of
the observed values. (You don't need to leave a space; ``,,'' would work on
the third line of the example just as well). Known limitations of the CVS
parser include these:
\begin{itemize}
\item No blanks at the end of the line are allowed!
\item You {\em must} have a cross-validation indicator, and it must mix
``in'' and ``out'' values (not all in).
\end{itemize}
\subsection*{Output of the csv parsing}
The parsed data are written into a named directory (which is created if it does
not exist). The key file in this directory is a shell script named {\tt
index.sh}. Executing this script produces streaming input in the format
expected by the auction. You can edit this script to produce test input,
shorter data series, or limit the number of variables. Three lines in the
script define the data for each variable:
\begin{enumerate}
\item name of the variable
\item attributes for this variable as space delimited strings/numbers
\item command that sends the variable to standard output (usually {\tt
echo}.
\end{enumerate}
As in JMP, square brackets in the name of a variable identify an indicator for
a category.
As a last step, it will be convenient to later stream the data into the auction
by concatenating a compressed version of the data. To build the compressed
archive, make the shell script executable ({\tt chmod +x index.sh}) and then
run the script with output to a file, {\tt .\/index.sh > data}). Then compress
the data using gzip into {\tt data.gz}. When the auction is run below, simply
cat the compressed data via stdin to the auction. Several examples in the
makefile in the {\tt auction} directory illustrate how this works.
\subsection{Data processing within the Auction}
Numerical data is read from a file aud converted into two vectors of {\tt
Column} objects. The read step is done by the routine {\tt
insert\_columns\_from\_file} called from the main function that sets up the
auction. A {\tt Column} is a wrapper (envelope) class for the column data
object that holds the actual data; this avoids the overhead of copying. Column
objects are lightweight. The {\tt ColumnData} object just reads numbers
(doubles, in particular), then computes summary characteristics (including the
number of unique values and means) from the input values in {\tt
init\_properties}. It knows nothing about the interpretation of names or
properties. As far as a {\tt Column} is concerned, names and descriptions are
simply strings. (The only conversion that happens in columns is to fill spaces
in names with the underscore character, converting for example ``the var'' into
``the\_var''.)
The auction code carefully examines the names of the leading input variables to
determine how to use the supplied cases. Cases may be of three types:
\begin{itemize}
\item Missing cases. These supply information about possible explanatory
variables, but the not the response. These are not predicted and are only used
for information about features (such as lagged variable values). These do not
appear in the saved data file produced at the end of an analysis and do not
appear in the data object ({\tt gsl\_data}) that supports the regression model.
\item In-sample or estimation cases. These are complete $(y_i,\xx_i)$ tuples
used to identify the model.
\item Out-of-sample or validation cases. These are complete cases, but will not
be used in the fitting process. They only appear for calculation of
predictions for validation purposes.
\end{itemize}
The input command-line argument ``x'' denote the number of leading cases which
are formally missing the response. These {\em must} be the leading cases in
the data file. These cases are neither used in fitting nor validation; they
are simply there for building predictive features. These rows are skipped over
when transferring the response ({\tt build\_model\_data}) and accepted features
into the auction. (Each expert knows rows to skip in the model. See the
function {\tt convert\_to\_model\_iterators} defined for the ExpertABC.) If
the leading column is named ``[in/out][in]'', then the first data column is
treated as a boolean indicator of the in-sample and out-of-sample cases. (For
extra cases, the values of any response column -- indicator and numerical value
-- are ignored.)
The parsing of the names of variables and the descriptions (property lists)
happens when the columns are convered into features. Features are initialized
from columns. As with columns, a feature is a wrapper hiding the particular
type of variable. {\tt ColumnFeatures} hold a column; other types, such as
unary features, hold a function that converts the values in a another feature.
The function {\tt add\_attributes\_from\_paired\_list}, for example, is called by
a column feature to convert the ``description string'' read by a column into
the paired property list used by a feature. Columns, for example, might simply
use this string as purely documenation, as in free text. Features, in
contrast, expect to find that this string has a paired list of terms.
Columns and Features live separately from the code that actually fits the
regression. The GSL routines, such as those in {\tt gsl\_regr}, work with a
distinct data object, essentially a plain old C array. The reason for this
duplication is to allow outside routines, such as features, to have a mix of
validation and estimation data, whereas the data inside the regression model is
{\em only} that which is used for fitting the model. Also, this separation
makes it easy to handle the use of split samples for validation. Code for {\tt
for} loops needs to be able to iterate over the elements of the data very
quickly, so we pack the estimation cases adjacent to each other by permuting
the input data. The validation cases are sorted away from the estimation cases
in the GSL objects, whereas they might be mixed together in the features.
\section{Experts} % --------------------------------------------------------------------------
The auction uses several types of experts. (In the code, these are identified
by an enumerated type.) Experts provide a way to search in a more 'depth
first' rather than 'breadth first' manner. With experts, one does not have to
examine, for example, every linear effect before considering a second-order
effect.
{\bf Reserved Stream Names} There are three reserved stream names. The default
stream name is ``MAIN''. This is the default stream assigned to explanatory
variables that do not name a stream. The second reserved name is ``LOCKED''.
Variables in the locked stream are forced into the model at the time of
initialization. Since all of these variables will appeaer in the list of model
features, they will automatically be considered in interactions with several
other experts. The third stream called ``CONTEXT'' holds variables that are
used to define neighborhoods of cases. Context variables are used to build
explanatory variables, but do not appear in the auction themselves.
\begin{description}
\item[Source experts] produce new features for consideration; in general, source
experts build variables from input data. The features from a source expert
could be generated from an algorithm or some other mechanism, but not from the
progress of the auction itself. Each problem generally has several source
experts (as identified by the 'stream' attribute in the data file). Splitting
the data into several sources allows the auction to discover collections of
variables of more interest rather than having to proceed through them all at
once. Source experts are assigned $\alpha$-wealth at the time that the auction
is initialized. Source experts continue to offer features until either all of
the associated features are accepted into the model or every feature has been
tried since the last variable was added to the model. Every unused feature is
tried at least once after the last added variable. If on this last pass, every
variable is rejected, then the expert no longer offers other variables.
Our implementation also generates interactions {\em within}
the features of stream. If $X_1$ and $X_2$ are from stream {\bf A} and $Z_1$
and $Z_2$ are from stream {\bf B}, then the corresponding source experts will
offer squares of the $X$s and $Z$s, $X_1*X_2$ and $Z_1*Z_2$, but not
cross-products such as $Z_1*X_2$. (Those can be formed using the
'interacts\_with' attribute of a feature, but is not routinely done.)
\item[Parasitic or scavenger experts] (or perhaps more politely called derived
experts) construct features from those that have already made an appearance in
the auction. These might be, for instance, various spatial interactions of a
feature that was initially rejected from the auction previously. Some versions
of the auction have used parasites that form interactions among variables in
the model; these are now handled elsewhere. The idea is that parasites ought
to be the ``voice of the forgotten'' or rejected features. Parasites obtain
$\alpha$-wealth from a tax on bids. The tax on bids is small since we expect a
lot of bids relative to the number of accepted features.
\item[Custom experts] are spawned when a feature is added to the model. By
default, the addition of a feature to the model generates an expert that offers
an interaction in that feature and any other features in the model. The
feature may itself add other experts as well. For example, a feature might add
time lags segmentation of itself (to allow spatial heterogeneity, for
example), or perhaps specify interactions with a specific collection of
features. Custom features allow the original expert to focus on a simple task,
say picking features from a large data source, rather than having the
distraction of following the status of features that join the model. Custom
experts are funded from the pay-out received when a variable joins the model.
As an example, one might have introduce a ``knot expert'' that offered possible
places to segment the effect of a feature (think turbo smoothing). This expert
would be bound to a specific feature accepted into the model. Because the
expert is tied to one specific feature, it is funded from that feature.
Suppose that the expert $\cal F$ recommends the feature $X$ to the auction,
placing some bid amount $b$. The variable $X$ joins the auction, earning
pay-out $\omega$. Some fraction of this pay-out goes directly back to the
recommending expert $\cal F$, the rest of the pay-out goes to experts related to
$X$. By default, $X$ is bound to an expert that builds interactions of $X$
with other features in the model. Assume that $X$ also comes with a custom
expert $\cal E$ that segments $X$ in the model, allowing nonlinear effects for
$X$. $\cal E$ unlike parasitic experts, gets created and funded from a tax on
the pay-out on $X$ when $X$ is accepted.\footnote{The code that builds custom
experts is in {\tt auction.Template.h}, specifically {\tt
pay\_winning\_expert}. Any feature added to the model automatically creates an
expert that builds interactions among variables added to the model. In
addition, a feature $X$ that has the attribute {\tt interact\_with} will also
generate an interaction between $X$ and all features that have an attribute
named by {\tt interact\_with}. For example, if {\tt interact\_with} has value
{\tt quarter}, then $X$ will be crossed with any feature that has the attribute
{\tt quarter}.}
\item[Calibration experts] serve a very narrow role of calibrating the fit of
the current model. These are funded at initialization and operate by-and-large
outside the usual auction process. They are experts more in name alone to
unify the coding.
\end{description}
It is worthwhile to review the funding of experts. The current algorithm funds
experts using ``taxes'' in order to avoid adding further wealth beyond the
initial wealth allocated at initialization. The auction funds source during
the initialization process, allocating the total initial $\alpha$-wealth given
to the auction among them (typically equally). (Calibration experts are also
funded at initialization, but out of a separate pool of wealth.) The auction
funds parasitic experts during the bidding process. Because parasitic experts
bid on features that are rejected, these are funded by a ``tax'' on bids placed
in the auction. For example, suppose a source expert $\cal E$ bids $\alpha =
0.01$ for the feature $X$. The auction taxes this bid at, say, 5\% and
distributes the tax revenue $0.01 \times 0.05 = 0.0005$ among those experts
that bid on rejected features. The auction funds custom experts that bid on
accepted features by taxing (at some possibly different -- and higher -- rate)
the pay-out $\omega$ made to an expert when a feature is accepted into the
model.
\clearpage
\section{Steps in the Auction} % -------------------------------------------------------------
This section describes the generation of experts in the auction and their
initial funding. These all basically use the universal bidding rule based on a
Cauchy distribution, with the added ability to ``spend it all'' before running
out of features.
{\em Prior to the start of the auction}, the software creates an initial set of
experts. These derive from the structure of the input explanatory variables
and chosen program options. The first experts are the parasite/scavenger
experts:
\begin{description}
\item[Rejected feature polynomials.] This expert builds polynomials in
rejected features to see if some simple nonlinearity might be present. If $X$
has been rejected, then the cubic version of this expert offers the bundle $X$,
$X^2$ and $X^3$ of three features to the auction. (If the linear term $X$ is
in the current model, the expert offers only $X^2$ and $X^3$.)
\item[Accepted/Rejected feature interactions.] This expert interacts features
that were rejected by the auction with those that were accepted.
\end{description}
These receive no initial alpha-wealth. They only get funded from taxes applied
to bids placed on variables considered for the auction.
The remainiong initial experts are ``source experts'' that recommend new
variables (basically, data read from an external file). For each named input
stream (the default is named ``main'' and it does not use the context stream),
the auction adds two experts:
\begin{description}
\item[Linear feature.] Recommends the actual input feature, as is. The expert
guarantees to make two passes over the list of variables in this stream before
it spends down all of its allocated alpha-wealth.
\item[Interactions.] This expert recommends interactions among the variables
within the stream.
\end{description}
These are funded by allocating the initial alpha-wealth of the auction, with
52\% of the wealth given to a stream going to the linear, and 48\% going to the
interactions. The difference makes sure we try linear terms before going after
interactions. (The associated code is in the file {\tt auction.test.cc} where
a comment indicates {\tt Assembling experts}.) In addition, the software will
add a calibration expert. Also, the software can add principal components or
RKHS basis vectors.
{\em Dynamic experts join the auction as the modeling continues.} The auction
adds additional experts ``on the fly'' when a variable gets added to the model.
If the added variable has the attribute {\tt interact\_with\_parent}, then the
auction gains an expert that will interact the newly added variable with any
variable from the named stream. (??? How does it use those that have already
been tried?) If the added variable has the integer-valued attribute
``max\_lag'', then an expert will offer up to this many lags of the added
variable. Finally, every added variable gets an expert that interacts it with
every other variable already in the model. Notice that this expert overlaps
with the source expert when the variables come from a common stream. For
example, if $X_1$ and $X_2$ come from the stream {\tt main} and first $X_1$ and
then $X_2$ are added to the model. The source stream for {\tt main} will offer
the interaction of these, and the dynamic stream will also recommend their
interaction. (That could be easily handled if the two experts bid for $X_1 *
X_2$ at the same time, but results in some wasted alpha if they win separate
bids.)
All of these dynmically-added experts are funded from a tax on the payout when
the variable is added. (See the code for {\tt pay\_winning\_expert} called by
{\tt auction\_next\_feature} in the file {\tt auction.Template.h}.) Many of
these experts bid only on a small list of features, meaning that they often run
out of features quickly. They can pass over them more than once, but in the
current implementaition experts with no features to recommend (now or in the
future) get harvested. Any remaining alpha is collected by the auction.
\section{Tests in Least Squares} % -----------------------------------------------------------
The value of the variable {\tt protection} (which is set in the constructor of
an auction) determines how the code treats the various test statistics. The
higher the level of the protection, the more conservative the computation of
the p-value associated with a test. The current implementation uses the
following methods, assuming that the current model includes $k$ predictors
with an intercept and has residuals in the $n$-vector $e$. Consider testing
the effect of adding $k_{new}$ predictors that produce residuals $e_{new}$.
\begin{enumerate}
\setcounter{enumi}{-1}
\item No protection. Construct the usual $F$ statistic for the added
variable(s),
\begin{equation}
F_0 = \frac{ dSS/k_{new} }{(e'e-dSS)/(n-1-k-k_{new})} \;.
\label{eq:f0}
\end{equation}
Obtain the p-value by comparing $F_0$ to the $F$-distribution with $k_new$ and
$n-1-k-k_{new}$ degrees of freedom. Equation \eqn{eq:dss} gives the familiar
expression for the change in the regression sum-of-squares obtained by adding
the additional variables.
\item White estimator, standard $F$ test. In this case, the White estimator is
used to compute the regression sum-of-squares, with an ``F-like'' statistic
\begin{equation}
F_1 = \frac{ dSS_{white}/k_{new} }{(e'e-dSS_{white})/(n-1-k-k_{new})} \;.
\label{eq:f1}
\end{equation}
Expression \eqn{eq:wdss} gives the White estimator used in the numerator of
$F_1$. The denominator of $F_1$ matches that of $F_0$. As before, obtain the
p-value by comparing $F_1$ to the $F$-distribution with the indicated degrees
of freedom.
\item White estimator, conservative $F$ test. The White estimator is again used
to find the regression SS, but now the denominator uses the residual sum of
squares {\em without} adding the new variable,
\begin{equation}
F_2 = \frac{ dSS_{white}/k_{new} }{e'e/(n-1-k-k_{new})} \;.
\label{eq:fstat}
\end{equation}
Calculate the p-value as for $F_1$.
\item Conservative p-value. Not yet implemented. The idea is to use a more
robust procedure to find the p-value in place of the F-distribution. I guess I
was thinking of something like a Bennett p-value here applied to the White F
stat. That seems way too conservative at this point, and it probably makes
more sense to adjust for possible dependence using a block calculation.
\end{enumerate}
\subsection{White variance estimates} % --------- ---------- ---------
Once the protection level in a least squares regression is larger than 0, we
use a White (or sandwich) estimator to find the numerator of the $F$-statistic
that is used to measure the statistical significance of an added variable(s).
The White estimate is generally proposed as a method of estimating a
heteroscedastic-robust standard error. It is used in finding a more robust
t-statistic. Consider the impact of adding one or more new features $X_{new}$
to a regression model that already contains the variables $X$ and has residuals
$e$. The first stage of testing sweeps out the prior explanatory variables $X$
from $X_{new}$, forming $Z$ defined as (Dean and Dong Yu omit this for speed.)
\begin{displaymath}
Z = (I-X(X'X)^{-1}X') X_{new} = (I-H_X) X_{new} \;.
\end{displaymath}
As motivation, consider testing the value of adding only one new feature, which
after sweeping out $X$ is the column vector $z$. The slope for the added
variable is $\hat\gamma = (z'e)/(z'z)$. The White estimate of the variance of
$\hat\gamma$ is
\begin{displaymath}
\var_w(\hat\gamma) = \frac{\sum_i (z_ie_i)^2} {(z'z)^2}
= \frac{z'E^2z} {(z'z)^2} \;,
\end{displaymath}
where $E$ is an $n \times n$ diagonal matrix with elements $E_{ii}=e_i$. (Note
that we use the residuals from the fit with $X$ alone, {\em not} both $X$ and
$z$. See \citet{fosterstine04:bank} for an explanation of this choice.) Hence, the
square of the robust $t$-statistic is
\begin{equation}
t^2 = \frac{\hat\gamma^2}{\var_w(\hat\gamma)}
= \frac{(z'e)^2}{z'E^2z} \;.
\label{eq:t2}
\end{equation}
Alternatively, we can obtain the same test statistic using the approach found
in building an $F$-statistic. This will be useful since we will consider
adding bundles of several features, and we will test these bundles as a group
rather than one at a time. Generally, an $F$-statistic in regression is the
ratio the change in the regression mean-squares to the residual mean-squares.
When adding $z$ to the model, the regression sum-of-squares increases by
$\hat\gamma' z'z \hat\gamma$. We need to change this expression to obtain an
$F$-statistic that corresponds to the robust $t$-statistic. In particular,
think of $z'z$ in $\hat\gamma' (z'z) \hat\gamma$ as proportional to the inverse
of the variance of $\hat\gamma$. We then replace the usual least squares
expression by that provided by the White estimator. The resulting $F$-like
statistic replaces
\begin{equation}
\frac{\hat\gamma' (z'z) \hat\gamma}{(e'e)/(n-q)}=
\hat\gamma\left(\frac{z'z}{(e'e)/(n-q)}\right) \hat\gamma
\end{equation}
by
\begin{equation}
\hat\gamma' (\var_w(\hat\gamma))^{-1} \hat\gamma =
\left(\frac{z'e}{z'z}\right) \left(\frac{z'E^2z}{(z'z)^2}\right)^{-1}
\left(\frac{z'e}{z'z}\right) = \frac{(z'e)^2}{z'E^2z} \;,
\label{eq:F2}
\end{equation}
which matches the squared robust $t$-statistic in \eqn{eq:t2}.
In the case of several added variables, we need to form the corresponding
matrices. The calculations are more messy, but follow the same steps. We
start by finding the increase in the regression sum-of-squares. Regress the
current residuals $e$ on $Z$, obtaining the partial coefficients $\hat\gamma =
(Z'Z)^{-1}Z'e$. The increase in the regression sum-of-squares due to this
partial regression is then the quadratic form
\begin{eqnarray}
\hat\gamma'(Z'Z)\hat\gamma \;,
\label{eq:dss}
\end{eqnarray}
and the $F$0-statistic normalizes this expression by an estimate of the error
variation.\footnote{The method {\tt change\_in\_rss} in gsl\_regr computes
$\Delta SS$ for the current regression.} The associated $F$-statistic for
adding $m$ new features to the model is
\begin{equation}
F = \frac{\Delta SS}{m \; s^2}
= \frac{1}{m} \; \hat\gamma' \var(\hat\gamma)^{-1} \hat\gamma \;,
\label{eq:F}
\end{equation}
where, if we continue to conservatively estimate the scale, $s^2 = (e'e)/(n-q)$.
To obtain the White version of the $F$-test, replace the variance estimate in
\eqn{eq:F} with the corresponding White estimator. The sandwich formula for
the variance of the coefficients is
\begin{displaymath}
\var_w(\hat\gamma) = (Z'Z)^{-1} Z'E^2Z (Z'Z)^{-1},
\quad E_{ij} = \delta_{ij} e_i\;.
\end{displaymath}
Hence, the White version of the $F$-statistic \eqn{eq:F} is
\begin{eqnarray}
F_w
&=& \smfrac{1}{m} \;
e'Z(Z'Z)^{-1}\left[(Z'Z)^{-1}Z'E^2Z(Z'Z)^{-1}\right]^{-1}(Z'Z)^{-1}Z'e \cr
&=& \smfrac{1}{m} \; e'Z (Z'E^2Z)^{-1} Z'e
\label{eq:Fw}
\end{eqnarray}
(Compare to the scalar version \eqn{eq:F2}.)\footnote{The function {\tt
white\_change\_in\_rss} passes the matrix shown in brackets in \eqn{eq:wdss} to
the function {\tt change\_in\_rss}.}
\subsection{White with Blocks}
Suppose that we treat the observations as possibly dependent in blocks. That
is, assume that the data $Y' = (Y_1', Y_2', \ldots, Y_K')$ come in $K$ clusters
with covariance matrix $V_k$ within the $k$th group:
\begin{displaymath}
Y = \mu + \epsilon, \quad \Var(\epsilon) =
\left(
\begin{array}{ccccc}
V_1 & 0 & \cdots & 0 \cr
0 & V_2 & \cdots & 0 \cr
\vdots & \vdots & \ddots & \vdots \cr
0 & 0 & \cdots & V_K
\end{array}
\right)
\end{displaymath}
The usual White estimator is robust to heteroscedasticity, but not
dependence. In this case, such as longitudinal data, we form a blocked White
estimator.
For convenience, suppose that each of the $K$ groups is of size $b$ so that $n
= K b$. The blocked White estimate of the variance of the least squares
estimates $\hat\beta$ based on a collection of $q$ features $X$ is
\begin{equation}
\var(\hat\beta) = (X'X)^{-1} \left(\sum_k X_k'e_ke_k'X_k\right) (X'X)^{-1},
\label{eq:blockwhite}
\end{equation}
where $e_k$ are the residuals within the $k$th block. To express these more
directly, let $B_k$ denote an $b \times n$ matrix with an $b\times b$ identity
matrix $I_b$ positioned to extract rows associated with block $k$:
\begin{equation}
B_k = \left(
\begin{array}{ccccccc}
0 & \cdots & 0 & \underbrace{I_b}_{\mbox{\scriptsize block $k$}} & 0 & \cdots & 0
\end{array}
\right) \;.
\label{eq:Bk}
\end{equation}
If $e = Y - X \hat\beta$ denote the residuals from the current fit, then $B_ke
= e_k$, the residuals in block $k$. The expression for the blocked variance
estimate \eqn{eq:blockwhite} then becomes
\begin{eqnarray}
\var(\hat\beta)
&=& (X'X)^{-1} \left(\sum_k X_k' B_k e \, e' B_k' X_k\right) (X'X)^{-1} \cr
&=& (X'X)^{-1} \left(\sum_k X_k' B_k (I-H)YY'(I-H) B_k' X_k\right)(X'X)^{-1}.
\label{eq:blockwhite1}
\end{eqnarray}
If $\ev Y = \mu$ lies in the column span of the current features $X$, then $H
\mu = \mu$ so that $(I - H)Y = \epsilon$, and the variance expression becomes
\begin{eqnarray}
\var(\hat\beta)
&=& (X'X)^{-1} \left(\sum_k X_k' B_k \eps \eps' B_k' X_k\right)(X'X)^{-1}\cr
&=& (X'X)^{-1} \left(\sum_k X_k' \eps_k \eps_k' X_k\right)(X'X)^{-1}
\label{eq:blockwhite2}
\end{eqnarray}
Taking expected values, the estimator is unbiased for the variance of the
estimator (ignoring issues of selection, of course)
\begin{equation}
\ev \var(\hat\beta)
= (X'X)^{-1} \left(\sum_k X_k' V_k X_k\right)(X'X)^{-1}.
\label{eq:blockwhite3}
\end{equation}
To gain some intuition about the blocked White estimator defined in
\eqn{eq:blockwhite}, it is helpful to compare it to a direct estimator of the
variance of the slope. Let $\hat\beta_k$ denote the estimated slope computed
within the $k$th block. It is then possible to show that blocked White
variance approximates the observed variance of $\hat\beta_k$ under some
conditions \citep{fosterlin10}. For convenience, assume that the features $X$
are identical within each block,
\begin{displaymath}
X =
\left( \begin{array}{c}
X_1 \cr X_2 \cr \vdots \cr X_K
\end{array} \right)
=
\left( \begin{array}{c}
X_1 \cr X_1 \cr \vdots \cr X_1
\end{array} \right)
\end{displaymath}
With this conformity, $\hat\beta_k = (X_1'X_1)^{-1}X_1'Y_k$, and the
overall slope fit to all of the data is the average of the $\hat\beta_k$:
\begin{displaymath}
\hat\beta = (X'X)^{-1}X'Y
= \frac{1}{K} \underbrace{(X_1'X_1)^{-1} \sum_k X_1'Y_k}_{\hat\beta_k}
= (X_1'X_1)^{-1} X_1' \ol{Y} \;,
\end{displaymath}
where the $b \times 1$ vector $\ol{Y}$ is the mean response under the repeated
conditions. Since the first row, for example, of each block is the same, the
estimator simply averages the first $y$'s and uses the average in the
regression.
This homogeneity shows up in the blocked White estimator as well. The variance
estimate \eqn{eq:blockwhite} reduces to
\begin{eqnarray}
\var(\hat\beta)
&=& \frac{1}{K^2}
(X_1'X_1)^{-1} \left(\sum_k X_1'e_k e_k'X_1\right) (X_1'X_1)^{-1} \cr
&=& \frac{1}{K^2}\sum_k (X_1'X_1)^{-1}X_1'(Y_k-X_1\hat\beta)
(Y_k-X_1\hat\beta)'X_1 (X_1'X_1)^{-1} \cr
&=& \frac{1}{K^2}\sum_k (\hat\beta_k-\hat\beta)(\hat\beta_k-\hat\beta)'\cr
&=& \frac{1}{K^2}\sum_k (\hat\beta_k-\ol{\hat\beta_k})
(\hat\beta_k-\ol{\hat\beta_k})' \cr
&=& \frac{K-1}{K^2} \var(\hat\beta_k) \;,
\end{eqnarray}
as in $\var(\ol{x}) = s_x^2/n$. The difference between the direct estimator
and the blocked White estimator lies in the information matrix $X_k'X_k$ for
the blocks. The larger the differences among the blocks, the greater the
difference between the direct and White estimates. \citet{fosterlin10} discuss
these differences further.
\section{Tests in Logistic Regression} % -----------------------------------------------------
The current implementation resembles the protections offered in linear models,
using the fact that a logistic regression is computed as a weighted least
squares. The distinction is with the White estimator: we use a Bennett bound
for logistic regression. The weights are used from the {\em prior} estimates
rather than endogenously. As in linear models, the variable {\tt protection}
determines the nature of the testing procedure (really, the calculation of the
p-value).
Given a set of explanatory variables in the model $X$, the logistic regression
solves the nonlinear estimating equations for $b$,
\begin{equation}
X'y = X'p_b, \quad \mbox{ where } p_b = \frac{1}{1+\exp(-X'b)} \;.
\label{eq:esteq}
\end{equation}
Note the similarity to the estimating equation (\aka, normal equation $X'y =
X'(Xb)$) used in linear equations; in both cases, we choose $b$ so that the
estimated values (either the probability $p$ or the fit $Xb$ reproduce the
correlation of $Y$ with the explanatory variables. (We subscript $p$ by the
coefficient $b$ as a reminder of this dependence; later we simplify this to
$p_1$ if the estimates are $b_1$. The same convention applies to other terms
such as matrices constructed from the estimated probabilities.)
Given a set of explanatory variables, we solve \eqn{eq:esteq} by using
iteratively reweighted least squares. The idea is a multivariate version of
using a linear approximation to find the zero of a function. Assume $f$ is an
arbitrary function and we'd like to find a point $x^{*}$ for which $f(x^{*}) =
0$. Our current guess is $x_0$. Then a linear Taylor approximation gives us
\begin{displaymath}
f(x) \approx f(x_0) + f'(x_0)(x - x_0)
\end{displaymath}
implies that (since $f(x^{*}) = 0$ and we hope that the zero of $f$ is $\approx
x^{*}$)
\begin{equation}
x = x_0 + \frac{f(x)-f(x_0)}{f'(x_0)} = x_0-\frac{f(x_0)}{f'(x_0)} \;.
\label{eq:newton}
\end{equation}
For logistic regression, $f$ is the derivative of the log of the likelihood.
Let $p$ denote the estimated probabilities from the current fit; define the
associated variance estimates as the diagonal of the matrix $V$,
\begin{displaymath}
V_{ii} = p_i (1-p_i), \quad i=1,\ldots, n\;.
\end{displaymath}
The estimating equation \eqn{eq:esteq} is the first derivative of the log of
the likelihood function. Deviations of $f(b) = X'(y-p_b)$ at the current
solution mean that we need to change $b$ to improve the solution. The second
derivative of the log-likelihood (which is the slope of the first derivative)
is the matrix $X'VX$. Hence, following the script of \eqn{eq:newton} we have
the classic Newton iteration
\begin{equation}
b_1 = b_0 - (X'V_0X)^{-1}X'(y-p_0) \;,
\label{eq:newton}
\end{equation}
where $V_0$ is the diagonal matrix computed from $p_0 = 1/(1+e^{-x'b_0})$,
which is the estimated probability at $b_0$.
Rather than directly follow this Newton iteration, we convert the estimation to
a regression problem so that we can use weighted least squares. (This allows
us to use the same code base for fitting linear and logistic regression
models.) Convergence of Newton's method produces a fixed point $b$ that
satisfies
\begin{displaymath}
b = b - (X'VX)^{-1}X'(y-p) \;.
\end{displaymath}
(Note: this expression suggests a way to form the sandwich estimator.) In order
to write this as a (weighted) least squares, note that in the usual expression
for a GLS estimator, the variance matrix appears twice:
\begin{displaymath}
\hat\beta = (X'W^{-1}X)^{-1}X'W^{-1}Y \;.
\end{displaymath}
We need to squeeze another $V$ into the Newton step \eqn{eq:newton}. We can
write this as a weighted least squares by forming a so-called pseudo-response
\begin{equation}
y^{*} = Xb + V^{-1}(y-p) \;.
\label{eq:ystar}
\end{equation}
We then compute the next iteration as
\begin{equation}
b_1 = (X'V_0X)^{-1}X'V_0y^{*} \;.
\label{eq:irls}
\end{equation}
Notice that the variance matrix $V_0$ appears in the expression for $b_1$
without an inverse that one might expect from the corresponding expression for
the WLS estimator. The explanation is the formation of the pseudo-response.
If we treat $Xb$ on the r.h.s. of \eqn{eq:irls} as fixed, then heuristically
$\var(y^{*}) = V^{-1}V V^{-1} = V^{-1}$ so $V_0$ {\em is} the inverser of the
variance matrix of $y^{*}$.
For testing, however, the weights are fixed at the values obtained by the
current model only, without an update for the variable under consideration.
This is in keeping with the second level of protection used in the linear
model. We have found this sufficiently useful in logistic regression as to
omit the more traditional updating. (It also keeps the code much simpler.)
The key function in the interface is {\tt add\_predictors\_if\_useful}.
\begin{enumerate}
\setcounter{enumi}{-1}
\item No protection. Construct the Wald $F$ statistic which is the
change in the log of the likelihood for the improvement in the model.
We prefer the Wald statistic to the score test (basically, $t$
statistics for the coefficient estimates) to avoid problems in which
the slope is poorly determined but highly useful (\eg, a separating
hyperplane -- or nearly so -- has been found).
\item Use Bennett's inequality. {\bf the current version only works
for one dim}. The values $y_i$ of the response are assumed to be
bounded within the range $m \le y_i \le M$. If there's only one
explanatory variable, the expression for the new slope introduced
into the logistic regression by adding the new variable $x_new$
becomes (simplifying the formula \ref{eq:irls})
\begin{displaymath}
b_{new} = \frac{z'y}{z'z}
\end{displaymath}
where $z$ and $y$ have been swept of the current explanatory variables in the
weighted inner product define by the current variables. That is, express the
WLS \eqn{eq:irls} estimate as the solution to an OLS with the weights
incorporated into the variables
\begin{equation}
b_1 = (X_v'X_v)^{-1}X_v'y^{*}_{v},
\quad X_v = V_0^{1/2}X, y^{*}_v = V_0^{1/2}y^{*} \;.
\label{eq:wls}
\end{equation}
Alternatively, return to the Newton iteration shown in \eqn{eq:newton}. One
need only test the size of the increment $(X'V_0X)^{-1}X'(y-p_0)$ in order to
decide whether to consider adding the proposed variable.
\end{enumerate}
\subsection{Comments on the implementation}
The same code base handles both linear and logistic regression. At the top
level in {\tt gsl\_model}, both linear and logistic regressions inherit from the
{\tt gsl\_regression} object. The distinction likes in the default choice of
the ``engine'' that handles the details of the calculations. Specifically,
engines are distinguished by how they define the inner product for all
calculations. (All regressions rely on the underlying model for inner products
such as matrix multiplication, inversion, and solving systems of equations.)
For a linear model, we use a standard engine that has the common dot-product
$\ip{x}{y} = \sum_i x_i y_i = x'y$. For a logistic regression, we use a
weighted dot product $\ip{x}{y} = \sum_i x_i y_i w_i$. The added complication
is that the weights change in a logistic regression; hence, there are
convenience functions that ``reweight'' the engine. Engines in the code (see
gsl\_engine.h) do not inherit from a common base (we never need a list of
engines); rather they implement common {\em policies}.
Functions handled by engines include those that seem clear ({\tt average,
sum\_of\_squares, blas\_ddot}) as well as the otherwise innocuous functions
\begin{itemize}
\item {\tt prepare\_vector\_for\_analysis}
\item {\tt insert\_analysis\_matrix}
\end{itemize}
Preparing a vector is a simple copy (OLS engine) or a copy plus scaling by the
square root of the weights (for the WLS engine, as seen in the expression for
the estimation shown in \eqn{eq:irls} above). Inserting a matrix copies the
matrix and scales the columns by the square root of the current weights
$\sqrt{w_i}$.
When a weighted engine is configured, the input includes a data object (one
that supports the required data policy). The weighted engine then extracts a
{\em pointer} from the data object to the initial weights to use in
calculations. Changes to these weights affect subsequent calculations, but
changes should be accompanied by telling the engine ({\tt
weights\_have\_changed}).
When a candidate feature is offered to a logistic model via {\tt
add\_predictor\_if\_useful}, the following steps occur: (Multiple features are
handled similarly.)
\begin{description}
\item{Data preparation} ({\tt prepare\_predictors}) The proposed feature (call
it $z$ is copied into local storage (from an iterator into a GSL matrix),
centered (with its mean stored, a weighted mean if $W_0 \ne I$), and scaled by
$\sqrt(W_0)$.
\item{Sweep current model} Current explanatory variables are swept from the
proposed new variable, producing ``residuals'' $z_{res}$. This is done using
the current weights $W_0$.
\end{description}
\bibliography{/Users/bob/work/references/stat}
\bibliographystyle{/Users/bob/work/papers/bst/rss}
\end{document}
|
import hashlib
import os
import re
from base64 import b64decode, b64encode
# Pattern to match the password with atleast one uppercase, one lowercase,
# one digit and one special character.
password_pattern = re.compile(r"(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-+_!@#$%^&*.,?])")
def encrypt(password: str) -> str:
password_bytes = password.encode("utf-8")
salt = os.urandom(64)
hashed = hashlib.scrypt(password_bytes, salt=salt, n=16384, r=8, p=1, dklen=128)
return f"{b64encode(salt).decode('utf-8')}.{b64encode(hashed).decode('utf-8')}"
def verify_password(password: str, hashed_password: str) -> bool:
salt, hashed = hashed_password.split(".")
salt = b64decode(salt.encode("utf-8"))
hashed = b64decode(hashed.encode("utf-8"))
hashed_password_bytes = hashlib.scrypt(
password.encode("utf-8"), salt=salt, n=16384, r=8, p=1, dklen=128
)
return hashed_password_bytes == hashed
|
const menuLinks = [
{ text: 'about', href: '/about' },
{
text: 'catalog',
href: '/catalog',
subLinks: [
{ text: 'all', href: '/catalog/all' },
{ text: 'top selling', href: '/catalog/top' },
{ text: 'search', href: '/catalog/search' },
],
},
{
text: 'orders',
href: '/orders',
subLinks: [
{ text: 'new', href: '/orders/new' },
{ text: 'pending', href: '/orders/pending' },
{ text: 'history', href: '/orders/history' },
],
},
{
text: 'account',
href: '/account',
subLinks: [
{ text: 'profile', href: '/account/profile' },
{ text: 'sign out', href: '/account/signout' },
],
},
];
const mainEl = document.querySelector('main');
mainEl.style.backgroundColor = 'var(--main-bg)';
mainEl.innerHTML = '<h1>SEI Rocks!</h1>';
mainEl.classList.add('flex-ctr');
const topMenuEl = document.querySelector('#top-menu');
topMenuEl.style.height = '100%';
topMenuEl.style.backgroundColor = 'var(--top-menu-bg)';
topMenuEl.classList.add('flex-around');
menuLinks.forEach(link => {
const aElement = document.createElement('a');
aElement.href = link.href;
aElement.textContent = link.text;
topMenuEl.appendChild(aElement);
});
const subMenuEl = document.querySelector('#sub-menu');
subMenuEl.style.height = '100%';
subMenuEl.style.backgroundColor = 'var(--sub-menu-bg)';
subMenuEl.classList.add('flex-around');
subMenuEl.style.position = 'absolute';
subMenuEl.style.top = '0';
const topMenuLinks = topMenuEl.querySelectorAll('a');
let showingSubMenu = false;
topMenuEl.addEventListener('click', (e) => {
e.preventDefault();
if (e.target.tagName !== 'A') return;
const clickedLink = e.target;
if (clickedLink.classList.contains('active')) {
clickedLink.classList.remove('active');
showingSubMenu = false;
subMenuEl.style.top = '0';
return;
}
topMenuLinks.forEach(link => link.classList.remove('active'));
clickedLink.classList.add('active');
showingSubMenu = link.subLinks && link.subLinks.length > 0; // Check if subLinks exist
if (showingSubMenu) {
buildSubMenu(clickedLink.subLinks);
subMenuEl.style.top = '100%';
} else {
subMenuEl.style.top = '0';
}
if (clickedLink.textContent === 'about') {
mainEl.innerHTML = '<h1>about</h1>';
}
});
subMenuEl.addEventListener('click', (e) => {
e.preventDefault();
showingSubMenu = false;
subMenuEl.style.top = '0';
topMenuLinks.forEach(link => link.classList.remove('active'));
mainEl.innerHTML = `<h1>${e.target.textContent}</h1>`;
});
function buildSubMenu(subLinks) {
subMenuEl.innerHTML = '';
subLinks.forEach(link => {
const aElement = document.createElement('a');
aElement.href = link.href;
aElement.textContent = link.text;
subMenuEl.appendChild(aElement);
});
}
|
import React from 'react';
import { withTranslation } from 'react-i18next';
import { Row, Col, Form } from 'react-bootstrap';
import { Formik } from 'formik';
import schema from './schema';
import '../Forms.scss';
const DashboardBusinessProfileFormsVideoUpload = ({ user, updateUser, t }) => {
return (
<Formik
className="form"
enableReinitialize
initialValues={{
profileVideoURL: user.profileVideoURL || '',
}}
validationSchema={schema}
>
{({ values, handleChange, handleSubmit, errors }) => {
return (
<Form noValidate onSubmit={handleSubmit}>
<Row className="mb-4">
<Col>
<div className="dashboard-business__profile__whitebox">
<Col sm={12}>
<Form.Group>
<p className="text-muted">
{t('dashboard.profile.addAVideo')}
</p>
<Form.Control
name="profileVideoURL"
value={values.profileVideoURL}
className=" form__control__account "
onChange={handleChange}
onBlur={() =>
updateUser()({
profileVideoURL: values.profileVideoURL,
})
}
isValid={
values.profileVideoURL && !errors.profileVideoURL
}
placeholder="Enter YouTube link i.e. https://www.youtube.com/watch?v=YOdZu5mjJjM"
/>
{errors.profileVideoURL && (
<p className="errorMessage">{errors.profileVideoURL}</p>
)}
</Form.Group>
</Col>
</div>
</Col>
</Row>
</Form>
);
}}
</Formik>
);
};
export default withTranslation('common')(
DashboardBusinessProfileFormsVideoUpload,
);
|
import { React, useState, useRef } from "react";
import Image from "next/image";
import { useSession } from "next-auth/react";
import { HiOutlineVideoCamera } from "react-icons/hi";
import { IoMdPhotos } from "react-icons/io";
import { BsEmojiSmile } from "react-icons/bs";
import { RiDeleteBin6Line } from "react-icons/ri";
import { useDispatch } from "react-redux";
import axios from "axios";
import { addPost } from "../public/src/features/postSlice";
const CreatePost = () => {
//implementing back to front (and in back it os in PostController.java @CrossOrigin)
const FACEBOOK_CLONE_URL_ENDPOINT = "http://localhost:9008/api/v1/post";
const { data: session } = useSession();
const dispatch = useDispatch(); //чтоб при нажатии отправка файлов шла в слайс (диспатчилась)
const inputRef = useRef(null);
const hiddenFileInput = useRef(null);
const [imageToPost, setImageToPost] = useState(null);
const handleClick = () => {
hiddenFileInput.current.click();
};
//функция загрузки поста при нажатии
const handleSubmit = (e) => {
e.preventDefault();
if (!inputRef.current.value) return;
const formData = new FormData();
formData.append("file", imageToPost);
console.log("imagetopost: " + imageToPost);
formData.append("post", inputRef.current.value);
formData.append("name", session?.user.name);
formData.append("email", session?.user.email);
formData.append("profilePic", session?.user.image);
//при клике, вся инфа о профиле, о контенте поста опубликовывается,посту даётся URL
//затем респонсом чистится поле для создания постов (текст и/или фото)
// и можно закетчить ошибку
axios
.post(FACEBOOK_CLONE_URL_ENDPOINT, formData, {
headers: { Accept: "application/json" },
})
.then((response) => {
inputRef.current.value = "";
dispatch(addPost(response.data));
console.log(response.data);
removeImage();
})
.catch((error) => {
console.log(error);
});
};
// картинка появляется в посте
const addImageToPost = (e) => {
const reader = new FileReader();
if (e.target.files[0]) {
reader.readAsDataURL(e.target.files[0]);
reader.onload = (e) => {
setImageToPost(e.target.result);
};
}
};
//картинка удаляется из поста
const removeImage = () => {
setImageToPost(null);
};
return (
<div className="bg-white rounded-md shadow-md text-gray-500 p-2">
<div className="flex p-4 space-x-2 item">
<Image
src={session?.user.image}
alt="inline logo"
height={40}
width={40}
className="rounded-full cursor-pointer"
/>
<form className="flex flex-1">
<input
className="rounded-full h-10 flex-grow focus:outline-none font-regular bg-gray-100 px-4"
type="text"
ref={inputRef}
placeholder={`What's on your mind, ${
session?.user.name.split(" ")[0]
}?`}
></input>
<button hidden onClick={handleSubmit}></button>
</form>
</div>
{imageToPost && (
<div
onClick={removeImage}
className="flex items-center px-4 py-2 space-x-4 filter hover:brightness-110 transotion duration-150 cursor pointer"
>
<img src={imageToPost} className="h-10 object-contain" />
<RiDeleteBin6Line className="h-8 hover:text-red-500" />
</div>
)}
<div className="flex justify-evenly py-2">
<div className="flex items-center p-1 space-x-1 flex-grow justify-center hover:cursor-pointer hover:bg-gray-100 rounded-md">
<HiOutlineVideoCamera sixe={20} className="text-red-500" />
<p className="font-regular text-gray-600">Live Video</p>
</div>
<div
onClick={handleClick}
className="flex items-center p-1 space-x-1 flex-grow justify-center hover:cursor-pointer hover:bg-gray-100 rounded-md">
<IoMdPhotos className="text-green-500" size={20} />
<p className="font-semibold text-gray-600">Photo/Video</p>
<input
ref={hiddenFileInput}
onChange={addImageToPost}
type="file"
accept="image/*"
hidden
/>
</div>
<div className="flex items-center p-1 space-x-1 flex-grow justify-center hover:cursor-pointer hover:bg-gray-100 rounded-md">
<BsEmojiSmile sixe={20} className="text-yellow-500" />
<p className="font-regular text-gray-600">Feeling/Activity</p>
</div>
</div>
</div>
);
};
export default CreatePost;
|
package com.example.myaffirmations
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.myaffirmations.Navigation.MainScreen
import com.example.myaffirmations.Navigation.navigation
import com.example.myaffirmations.ui.theme.MyAffirmationsTheme
import com.example.myaffirmations.ui.theme.backgroundCharcoal
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.qualifiers.ApplicationContext
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyAffirmationsTheme {
Surface(color = MaterialTheme.colorScheme.background) {
MainScreen(context =applicationContext )
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyAffirmationsTheme {
Greeting("Android")
}
}
|
# IMPORT NECESSARY LIBRARIES
import time
import pyautogui
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from datetime import datetime, date, timedelta
import config
# SETUP (access website, filter for information)
# path = "C:\Downloads\chromedriver.exe"
# browser = webdriver.Chrome(path)
# access public notice website
# browser.get('https://www.georgiapublicnotice.com/')
# browser.implicitly_wait(100)
# browser.maximize_window()
# initialSetupParameters scrapes either COUNTY or PUBLICATION
def setSearch(browser):
# First, click the dropdown toggle to ensure the dropdown is visible
dropdown_toggle = WebDriverWait(browser, 100).until(
EC.element_to_be_clickable((By.ID, "ctl00_ContentPlaceHolder1_as1_pnlQuickSearch")))
dropdown_toggle.click()
# Now that the dropdown is open, select the "FORECLOSURES" option from the <select> element
select_element = WebDriverWait(browser, 100).until(
EC.presence_of_element_located((By.ID, "ctl00_ContentPlaceHolder1_as1_ddlPopularSearches")))
dropdown = Select(select_element)
# Select the option by its visible text or value. Here we're selecting by visible text
try:
# Try to select "Foreclosures" first
dropdown.select_by_visible_text("Foreclosures")
except NoSuchElementException:
try:
# If "Foreclosures" is not found, try "Foreclosure"
dropdown.select_by_visible_text("Foreclosure")
except NoSuchElementException:
# Handle the case where neither option is found
print("Neither 'Foreclosures' nor 'Foreclosure' options were found.")
# Consider adding more error handling here, e.g., logging or raising an error
# quick search for foreclosures --> triggers search
# setupParameter sets start/end dates + filters quick search to foreclosures
def setDate(browser, currentDate):
# print("in setup "+currentDate.strftime("%m/%d/%Y"))
# access date range drop down menu
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.ID,"ctl00_ContentPlaceHolder1_as1_divDateRange"))).click()
# access custom date range
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.ID,"ctl00_ContentPlaceHolder1_as1_rbRange"))).click()
# set start date
ctrl_Character = config.keys['control_key']
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.ID,"ctl00_ContentPlaceHolder1_as1_txtDateFrom"))).click()
pyautogui.keyDown(ctrl_Character)
pyautogui.press("a")
pyautogui.keyUp(ctrl_Character)
pyautogui.press("backspace")
pyautogui.write(currentDate) # define current date later
# set end date
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.ID,"ctl00_ContentPlaceHolder1_as1_txtDateTo"))).click()
pyautogui.keyDown(ctrl_Character)
pyautogui.press("a")
pyautogui.keyUp(ctrl_Character)
pyautogui.press("backspace")
pyautogui.write(currentDate)
# Finally, click the search button to apply the filter
search_button = WebDriverWait(browser, 100).until(
EC.element_to_be_clickable((By.ID, "ctl00_ContentPlaceHolder1_as1_btnGo")))
search_button.click()
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.NAME,"ctl00$ContentPlaceHolder1$as1$btnGo"))).click()
WebDriverWait(browser, 100).until(EC.url_changes)
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.ID,"ctl00_ContentPlaceHolder1_as1_divDateRange"))).click()
# scrape facilitates all web scraping actions
def scrape(browser, current_date):
# create initial df to hold information
dfall = pd.DataFrame(columns = ["noticeDate","webURL","pubName","location","Content","Hash"])
# increase results per page to 50
WebDriverWait(browser, 100).until(EC.visibility_of_element_located((By.ID,"ctl00_ContentPlaceHolder1_WSExtendedGridNP1_GridView1_ctl01_ddlPerPage"))).click()
pyautogui.write("50")
pyautogui.press("enter")
time.sleep(3)
# view one record
buttons = browser.find_element(By.ID,"ctl00_ContentPlaceHolder1_WSExtendedGridNP1_GridView1_ctl03_btnView2")
buttons.click()
WebDriverWait(browser, 100).until(EC.url_changes)
time.sleep(15)
# TEST: grab notice content
backBtn = browser.find_element(By.ID, "ctl00_ContentPlaceHolder1_PublicNoticeDetailsBody1_hlBackFromBody")
backBtn.click()
def ga_publicnotice(siteurl, start_date, end_date):
# access chrome driver
browser = webdriver.Chrome()
# opening the web to scrape
browser.get(siteurl)
browser.maximize_window
# set up dataframe
# Date:Publication date, Source:Publication Website, Label:?,
dfall = pd.DataFrame(columns = ["Date","Source","Label","Area","Content","Hash"])
# Convert string dates to datetime objects
start_dt = datetime.strptime(start_date, '%m/%d/%Y')
end_dt = datetime.strptime(end_date, '%m/%d/%Y')
# Iterate over each day in the date range
current_date = start_dt
while current_date <= end_dt:
current_date_str = current_date.strftime('%m/%d/%Y')
# Set the search parameters for the current date
setSearch(browser) # This sets the category; ensure it clicks the search button if needed
setDate(browser, current_date_str) # This sets the date and should trigger the search
# Scrape the data for the current date
daily_notices = scrape(browser, current_date_str)
# Append the daily notices to the collective DataFrame
dfall = pd.concat([dfall, daily_notices], ignore_index=True)
# Move to the next day
current_date += timedelta(days=1)
#end_date = datetime.strptime(end_date, '%m/%d/%Y')
#current_date = end_date
#setSearch(browser)
#flag=0
#while True: #iterating the through the date
#current_date_str = str(current_date.strftime('%m/%d/%Y'))
#if current_date_str == start_date:
#break
#current_date = current_date - timedelta(days = 1)
#print(current_date_str)
#print ("current_date {}".format(current_date))
#current_date_str = str(current_date.strftime('%m/%d/%Y'))
#setDate(browser,current_date_str)
#time.sleep(5)
# initialSetupParameters(browser)
browser.quit()
print(dfall)
return dfall
|
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { UsersService } from '../services/users.service';
import { UserDTO } from '../dto/user.dto';
import { UserUpdateDTO } from '../dto/update-user.dto';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post('register')
public async registerUser(@Body() body: UserDTO){
return await this.usersService.createUser(body);
}
@Get ('all')
public async findAllUsers(){
return await this.usersService.findUsers();
}
@Get (':id')
public async findUserById(@Param("id") id:string){
return await this.usersService.findUserById(id);
}
@Put ('edit/:id')
public async updateUser (@Param("id") id:string, @Body() body: UserUpdateDTO){
return await this.usersService.updateUser(body,id)
}
@Delete ('delete/:id')
public async deleteUser (@Param("id") id:string){
return await this.usersService.deleteUser(id)
}
}
|
import 'package:bloacktut/features/auth/presentation/pages/signup_page.dart';
import 'package:flutter/material.dart';
import '../../../../core/theme/app_pallete.dart';
import '../widgets/auth_field.dart';
import '../widgets/auth_gradient_button.dart';
class LoginPage extends StatefulWidget {
static route()=>MaterialPageRoute(builder: (context)=>const LoginPage());
const LoginPage({Key? key}) : super(key: key);
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final formKey = GlobalKey<FormState>();
final emailController = TextEditingController();
final passwordController = TextEditingController();
@override
void dispose() {
// TODO: implement dispose
emailController.dispose();
passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Sign IN.",
style: TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
),
const SizedBox(
height: 30,
),
AuthField(
hintText: "Email",
controller: emailController,
),
const SizedBox(height: 15),
AuthField(
hintText: "Password",
controller: passwordController,
isObs: true,
),
const SizedBox(height: 20),
AuthGradientButton(ButtonText: "Sign In", onPressed: () { },),
const SizedBox(height: 20),
GestureDetector(
onTap: (){
Navigator.push(context, SignupPage.route());
},
child: RichText(
text: TextSpan(
text: 'Don\'t have an account? ',
style: Theme.of(context).textTheme.titleMedium,
children: [
TextSpan(
text: 'Sign Up',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: AppPallete.gradient2,
fontWeight: FontWeight.bold),
)
])),
)
],
),
),
),
);
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Slider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;
class SliderController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => 'index']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$sliders = Slider::all();
return response()->json([
'message' => 'success',
'data' => $sliders
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'nama_slider' => 'required',
'deskripsi' => 'required',
'gambar' => 'required|image|mimes:jpg,png,jpeg,svg'
]);
if ($validator->fails()) {
return response()->json(
$validator->errors(),
422
);
}
$input = $request->all();
if ($request->has('gambar')) {
$gambar = $request->file('gambar');
$nama_gambar = time() . rand(1, 9) . '.' . $gambar->getClientOriginalExtension();
$gambar->move('uploads', $nama_gambar);
$input['gambar'] = $nama_gambar;
}
$sliders = Slider::create($input);
return response()->json([
'message' => 'success',
'data' => $sliders
]);
}
/**
* Display the specified resource.
*
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function show(Category $category)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function edit(Category $category)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Slider $Slider)
{
$validator = Validator::make($request->all(), [
'nama_slider' => 'required',
'deskripsi' => 'required',
]);
if ($validator->fails()) {
return response()->json(
$validator->errors(),
422
);
}
$input = $request->all();
if ($request->has('gambar')) {
File::delete('uploads/' . $Slider->gambar);
$gambar = $request->file('gambar');
$nama_gambar = time() . rand(1, 9) . '.' . $gambar->getClientOriginalExtension();
$gambar->move('uploads', $nama_gambar);
$input['gambar'] = $nama_gambar;
} else {
unset($input['gambar']);
}
$Slider->update($input);
return response()->json([
'message' => 'berhasil update slider',
'data' => $Slider
]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Category $Slider
* @return \Illuminate\Http\Response
*/
public function destroy(Slider $Slider)
{
File::delete('uploads/' . $Slider->gambar);
$Slider->delete();
return response()->json([
'message' => 'success'
]);
}
}
|
import { useState, useEffect } from "react";
import Dropdown from "./Dropdown";
import useFetchPeople from "./hooks/useFetchPeople";
import useFetchHomeworldMapping from "./hooks/useFetchHomeworldMapping";
const PeopleList = () => {
// would typically store these values in redux once fetched,
// but storing in useState hook b/c of time constraint
const people = useFetchPeople();
const homeworldURLtoHomeworldMapping = useFetchHomeworldMapping(people);
const [inputText, setInputText] = useState("");
const [filterValue, setFilterValue] = useState("");
const [filteredPeople, setFilteredPeople] = useState([]);
const homeWorldOptionList = [{ value: "", label: "None" }];
homeworldURLtoHomeworldMapping.forEach((key, value) => {
homeWorldOptionList.push({ value: value, label: key });
});
let inputHandler = (e) => {
var lowerCase = e.target.value.toLowerCase();
setInputText(lowerCase);
};
useEffect(() => {
let filteredPeople = [...people];
if (filterValue) {
filteredPeople = filteredPeople.filter(
(person) => person.homeworld === filterValue
);
}
if (inputText) {
filteredPeople = filteredPeople.filter((person) =>
person.name.toLowerCase().includes(inputText)
);
}
setFilteredPeople(filteredPeople);
}, [filterValue, inputText]);
let peopleList;
if (filterValue || inputText) {
peopleList = (
<ul>
{filteredPeople.map((person, i) => (
<li key={i}>
{person.name} |{" "}
{homeworldURLtoHomeworldMapping.get(person.homeworld)}
</li>
))}
</ul>
);
} else if (people.length !== 0) {
peopleList = (
<ul>
{people.map((person, i) => (
<li key={i}>
{person.name} |{" "}
{homeworldURLtoHomeworldMapping.get(person.homeworld)}
</li>
))}
</ul>
);
} else {
peopleList = <div>Loading...</div>;
}
return (
<div>
<h2>Person | Home-world are listed below</h2>
<Dropdown
label="Filter by home-world: "
options={homeWorldOptionList}
value={filterValue}
onChange={(event) => setFilterValue(event.target.value)}
/>
<div>
<input
type="text"
placeholder="Name"
value={inputText}
onChange={inputHandler}
/>
</div>
{peopleList}
</div>
);
};
export default PeopleList;
|
<?php
namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\CreatePageRequest;
use App\Http\Requests\Backend\UpdatePageRequest;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class PageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$pages = DB::table('pages')->orderBy('id', 'desc')->paginate(4);
return view('backend.pages.index', compact('pages'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$pages = Page::where('status', 1)->get();
return view('backend.pages.create', compact('pages'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(CreatePageRequest $request)
{
$image = $request->file('image');
if(!empty($image)) {
$name = 'pages_' . time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('/uploads/pages'), $name);
}else {
$name = 'noPhoto.png';
}
Page::create([
'title' => $request->title,
'content'=>$request->content,
'image'=>$name,
'status'=>$request->status,
]);
return redirect()->route('backend.pages.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$page = Page::find($id);
return view('backend.pages.edit', compact('page'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(UpdatePageRequest $request, $id)
{
$page = Page::find($id);
$page->title = $request->title;
$page->content = $request->content;
$page->status = $request->status;
$image = $request->file('image');
if ($_POST['hidden'] == "0") {
$page->image = 'noPhoto.png';
}
else if (empty($_FILES['image']['tmp_name']) || !is_uploaded_file($_FILES['image']['tmp_name'])){
$page->image=$page->image;
}
else{
$name = 'page_' . time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('/uploads/pages'), $name);
$page->image=$name;
}
$page->save();
return redirect()->route('backend.pages.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Page::where('id', $id)->delete();
return response()->json(['message','ugurlu'], 200);
}
}
|
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-user-reg',
templateUrl: './user-reg.component.html',
styleUrls: ['./user-reg.component.css']
})
export class UserRegComponent {
register: FormGroup;
checkcredit: FormGroup;
isValidUser: boolean = false;
isCheck: boolean = false;
score: any;
errMsg: string = '';
isformValid:boolean=false;
success: any;
userData: boolean=false;
userInfo: any;
countriesList: any;
stateList: any;
cityList: any;
constructor(private fb: FormBuilder, private http: HttpClient, private router:Router) {
this.checkcredit = this.fb.group({
pan: [
'',
[
Validators.required,
Validators.minLength(10),
Validators.pattern(
/^[A-Z]{3}[ABCFGHLJPTF]{1}[A-Z]{1}[0-9]{4}[A-Z]{1}$/
),
],
],
});
this.register = this.fb.group({
firstName: ['',[Validators.required, Validators.minLength(3), Validators.pattern(/^[a-zA-Z]*$/)]],
lastName: ['',[Validators.required, Validators.minLength(3), Validators.pattern(/^[a-zA-Z]*$/)]],
gender: [''],
mobile: ['',[Validators.required, Validators.minLength(10), Validators.pattern(/^[6-9][0-9]{9}$/)]],
email: ['',[Validators.required, Validators.pattern(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)]],
password: ['',[Validators.required, Validators.minLength(8)]],
address: [''],
state: [''],
city: [''],
country: [''],
pincode: ['']
});
}
ngOnInit(): void {}
checkCreditScore() {
if (this.checkcredit.valid) {
debugger
this.http
.get<any>('http://localhost:8080/checkCredit')
.subscribe((responce) => {
console.log(responce)
this.score = responce.score;
if (this.score >= 750) {
this.isValidUser = true;
this.errMsg=''
} else {
this.errMsg = 'Your Not Elegible for Registration';
this.isValidUser = false;
}
});
} else {
this.isCheck = true
}
}
userRegistration() {
if(this.register.valid){
let req={
firstName:this.register.value.firstName,
lastName:this.register.value.lastName,
mobileNo:this.register.value.mobile,
email:this.register.value.email,
password:this.register.value.password,
gender:this.register.value.gender,
address:this.register.value.address,
state:this.register.value.state,
city:this.register.value.city,
country:this.register.value.country,
pincode:this.register.value.pincode
}
let url='http://localhost:8090/addUser'
this.http
.post<any>(url, req).subscribe(responce =>{
this.userInfo = responce;
this.success='User details saved successfully'
// this.router.navigate(['/customerlist'])
this.isValidUser=false;
this. userData=true;
})
}else{
this.success=''
this.userData=false;
}
}
goToRegister(){
this.userData=false
this.checkcredit.reset()
}
country(){
let url='http://localhost:8090/countries'
this.http
.get(url)
.subscribe((responce:any)=>{
this.countriesList=responce
})
}
getStates(event:any){
console.log(event.target.value)
this.http
.get('http://localhost:8090/states', event.target.value).subscribe((responce:any) =>{
this.stateList = responce;
})
}
getCities(event:any){
console.log(event.target.value)
this.http
.get('http://localhost:8090/cities', event.target.value).subscribe((responce:any) =>{
this.cityList = responce;
})
}
}
|
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { AppService } from 'src/app/app.service';
import { Constant } from 'src/app/resources/constants/constants';
import { setPic } from '../../models/onboarding.model';
import { SetProfilePicComponent } from '../../../general-components/set-profile-pic/set-profile-pic.component';
@Component({
selector: 'app-profile-picture',
templateUrl: './profile-picture.component.html',
styleUrls: ['./profile-picture.component.scss']
})
export class ProfilePictureComponent implements OnInit {
firstname: string = this.app.utilities.getUserFirstName();
@Output() stepNumber = new EventEmitter<number>();
fileSystemImage: any = 'assets/images/cover.png';
selectedImage: any = "assets/images/avatar1.svg";
selectedHeader: string = ""
imageLoad!: setPic
innerHeight = window.innerHeight - (450);
avatars: string[] = [
'assets/images/avatar1.svg', 'assets/images/avatar2.svg', 'assets/images/avatar3.svg',
'assets/images/avatar4.svg', 'assets/images/avatar5.svg', 'assets/images/avatar6.svg',
'assets/images/avatar7.svg', 'assets/images/avatar8.svg', 'assets/images/avatar9.svg',
'assets/images/avatar9.svg', 'assets/images/avatar11.svg', 'assets/images/avatar12.svg',
];
loading: boolean = false;
strippedImage: any;
headerLoading: boolean = true;
selectImage: boolean = false;
File!: File;
profileImage= this.app.utilities.getUserProfileImage();
backgroundImage= this.app.utilities.getUserHeaderImage();
imageUrl = Constant.IMAGE_URL
constructor(
private dialog: MatDialog,
private app: AppService
) { }
ngOnInit(): void {
}
setImage(image: any){
// this.fileSystemImage = selectedImage
this.backgroundImage = null
let file: File = image.target.files[0]
this.File = <File>image.target.files[0];
let reader = new FileReader();
reader.addEventListener(
"load",
() => {
this.fileSystemImage = reader.result;
this.setHeader()
},
false
);
if (file) {
reader.readAsDataURL(file);
}
}
setHeader(){
this.headerLoading = true
this.app.snackbar.open('Setting Profile Header....', 'Dismiss', {
duration:Constant.TIMEOUT_DURATION
})
let formData = new FormData();
formData.append('file', this.File, this.File.name)
formData.append('email', this.app.utilities.getUserEmail())
formData.append('user_id', this.app.utilities.getUserId())
formData.append('img_type', 'c')
this.app.onboardingService.setPic(formData)
.subscribe({
next: (res: any) => {
this.headerLoading = false
this.app.snackbar.open(res['message'], 'Dismiss', {
duration:Constant.TIMEOUT_DURATION
})
this.backgroundImage = res.img
this.app.setHeaderPic(res.img)
},
error: (error) => {
this.headerLoading = false
this.app.snackbar.open(error, 'Dismiss', {
duration:Constant.TIMEOUT_DURATION
})
}
});
}
selectPicture(){
this.selectImage = true
// let dialogConfig = new MatDialogConfig();
// dialogConfig.width = '80%';
// dialogConfig.minHeight = '32vh';
// dialogConfig.panelClass = 'custom-popup';
// dialogConfig.position = {bottom: '0%'}
// dialogConfig.disableClose = true;
// this.dialog
// .open(SetProfilePicComponent, dialogConfig)
// .afterClosed()
// .subscribe((res: any) => {
// if(res){
// this.selectedImage = res
// this.setProfilePic()
// }
// });
}
selectImages(event: any){
if (event == 'close') {
this.selectImage = false
}else{
this.File = event
// this.profileImage = event.name
let reader = new FileReader();
reader.addEventListener(
"load",
() => {
this.selectedImage = reader.result;
},
false
);
if (this.File) {
reader.readAsDataURL(this.File);
}
this.setProfilePic()
}
}
setProfilePic(){
this.loading = true
this.app.snackbar.open('Setting Profile Picture....', 'Dismiss', {
duration:Constant.TIMEOUT_DURATION
})
let file: File = this.File
let formData = new FormData();
formData.append('file', file, file.name)
formData.append('email', this.app.utilities.getUserEmail())
formData.append('user_id', this.app.utilities.getUserId())
formData.append('img_type', 'p')
this.app.onboardingService.setPic(formData)
.subscribe({
next: (res: any) => {
this.loading = false
this.profileImage = res.img
this.app.snackbar.open(res['message'], 'Dismiss', {
duration:Constant.TIMEOUT_DURATION
})
this.app.setProfilePic(res.img)
},
error: (error) => {
this.loading = false
this.app.snackbar.open(error, 'Dismiss', {
duration:Constant.TIMEOUT_DURATION
})
}
});
}
next(){
this.stepNumber.emit(2)
}
}
|
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'package:chatapp/cubit/cubit.dart';
import 'package:chatapp/cubit/states.dart';
import 'package:chatapp/styles/colors.dart';
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../models/post_model.dart';
class FeedsScreen extends StatelessWidget {
const FeedsScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocConsumer<SocialCubit,SocialStates>(
listener: (context,state){},
builder: (context,state)
{
return ConditionalBuilder(
condition: SocialCubit.get(context).posts.length!=null &&SocialCubit.get(context).model!=null,
builder: (context)=> SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Column(
children: [
Card(
clipBehavior: Clip.antiAliasWithSaveLayer,
margin: EdgeInsets.all(8.0),
elevation: 6.0,
child: Stack(
alignment: AlignmentDirectional.bottomEnd,
children: [
Image(
image: NetworkImage('https://img.freepik.com/free-photo/top-view-people-hugging-illuminating-floor_23-2148791675.jpg?w=1060&t=st=1671660352~exp=1671660952~hmac=b3496701d08a5480b111f4dc50fd5540223d036c4ddbd985a3a4d7eb63818892'),
fit: BoxFit.cover,
height: 200.0,
width: double.infinity,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'communicate with friends',
style: Theme.of(context).textTheme.subtitle1!.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
),
),
],
),
),
ListView.separated(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context,index)=>buildPost(SocialCubit.get(context).posts[index],context,index),
separatorBuilder: (context,index)=>SizedBox(height: 8.0,),
itemCount: SocialCubit.get(context).posts.length,
),
SizedBox(height: 8.0,),
],
),
),
fallback:(context)=> Center(child: CircularProgressIndicator()),
);
},
);
}
Widget buildPost(SocialPostModel postmodel,context,index) => Card(
clipBehavior: Clip.antiAliasWithSaveLayer,
elevation: 8.0,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start ,
children: [
Row(
children: [
CircleAvatar(
radius: 25.0,
backgroundImage: NetworkImage('${postmodel.image}'),
),
SizedBox(width: 10.0,),
Expanded(
child: Column(
crossAxisAlignment:CrossAxisAlignment.start ,
children: [
Row(
children: [
Text(
'${postmodel.name}',
style: TextStyle(
fontWeight: FontWeight.bold,
height: 1.4
),
),
SizedBox(width: 6.0,),
Icon(
Icons.verified_sharp,
color: Colors.blue,
size: 16.0,
),
],
),
Text(
'${postmodel.dateTime}',
style: Theme.of(context).textTheme.caption!.copyWith(
height: 1.4,
),
),
],
),
),
SizedBox(width: 15.0,),
IconButton(
onPressed: (){},
icon:Icon(
Icons.more_horiz,
size: 16.0,
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0),
child: Container(
width: double.infinity,
height: 1.0,
color: Colors.grey[300],
),
),
Text(
'${postmodel.text}',
style: Theme.of(context).textTheme.subtitle1!.copyWith(
fontSize: 14.0,
height: 1.3,
color: Colors.black,
fontWeight: FontWeight.w600,
),
),
// Padding(
// padding: const EdgeInsets.only(
// bottom: 10.0,
// top: 5.0,
// ),
// child: SizedBox(
// width: double.infinity,
// child: Wrap(
// children: [
// Padding(
// padding: const EdgeInsets.only(right: 6.0),
// child: SizedBox(
// height: 25.0,
// child: MaterialButton(
// minWidth: 1.0,
// padding: EdgeInsets.all(0.0),
// onPressed: (){},
// child: Text(
// '#softagi',
// style: Theme.of(context).textTheme.caption!.copyWith(
// color: defaultColor,
// ),
// ),
// ),
// ),
// ),
// ],
// ),
// ),
// ),
if(postmodel.postImage!='')
Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Container(
width: double.infinity,
height: 160.0,
decoration: BoxDecoration
(
borderRadius:BorderRadius.circular(4.0),
image: DecorationImage(
image: NetworkImage('${postmodel.postImage}'),
fit: BoxFit.cover,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Row(
children: [
Expanded(
child: InkWell(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Row(
children: [
Icon(
Icons.favorite_border_outlined,
size: 20.0,
color: Colors.red,
),
SizedBox(
width: 5.0,
),
Text(
'${SocialCubit.get(context).likes[index]++}',
style: Theme.of(context).textTheme.caption,
),
],
),
),
onTap: (){},
),
),
Expanded(
child: InkWell(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Icon(
Icons.chat_bubble_outline,
size: 20.0,
color: Colors.amber,
),
SizedBox(
width: 5.0,
),
Text(
'120 comments',
style: Theme.of(context).textTheme.caption,
),
],
),
),
onTap: (){},
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: Container(
width: double.infinity,
height: 1.0,
color: Colors.grey[300],
),
),
Row(
children: [
Expanded(
child: InkWell(
child: Row(
children: [
CircleAvatar(
radius: 18.0,
backgroundImage: NetworkImage('${SocialCubit.get(context).model!.image}'),
),
SizedBox(width: 10.0,),
Text(
'write a comment',
style: Theme.of(context).textTheme.caption!.copyWith(),
),
],
),
onTap: (){},
),
),
InkWell(
child: Row(
children: [
Icon(
Icons.favorite_border_outlined,
size: 20.0,
color: Colors.red,
),
SizedBox(
width: 5.0,
),
Text(
'LIKE',
style: Theme.of(context).textTheme.caption,
),
],
),
onTap: ()
{
SocialCubit.get(context).sendLikes(SocialCubit.get(context).postId[index]);
},
),
],
),
],
),
)
);
}
|
#if !defined(SERVER_OP_H)
#define SERVER_OP_H
//#include <list.h>
#include <pthread.h>
/*
** Funzioni necessarie all'esecuzione delle richieste ricevute all'interno
** dell'object store.
*/
/*
** Questa è la struttura di gestione dei client, (dove ogni client ha un lock
** per la proprio cartella.)
** @param: -name: è il nome del client connesso.
** -path: è il path della sa directory.
** (-mtx: è il lock dedicato al client.)
*/
typedef struct clients_t {
char* name;
char* path;
//pthread_mutex_t mtx;
}cl_t;
/*
** Questa struttura contiene le statistiche di cui il server dovrà tenere traccia.
** @param: -conn: numero di connessioni attive.
** -n_obj: numero di oggetti salvati nell'object store.
** -size: dimensione totale dell'object store.
*/
typedef struct stats_t {
int conn;
int n_obj;
int size;
}st_t;
/*
** Questa funzione invia il messaggio di OK nel socket utilizzato per la connessione.
** @param: -conn: è il descrittore del socket.
*/
void ok(long conn);
/*
** Questa funzione scrive il messaggio di KO sul socket utilizzato per la conessione.
** @param: -conn: è il descrittore del socket.
** -str: è una stringa per comprendere meglio l'errore.
** -strerr: è il tipo di errore verificato. (da utilizzare con strerror(errno)).
*/
void ko(long conn, char* str, char*strerr);
/*
** Questa funzione invia il messaggio DATA sul socket di connessione.
** @param: -conn: è il descrittore del socket.
** -data: è il blocco dati da inviare.
** -len: è la lunghezza del blocco dati.
*/
void data(long conn, void* data, size_t len);
/*
** Crea una nuova cartella all'interno della cartella "data", con nome "name",
** solo se questo nome non è già esistente, altrimenti vi si connette soltanto.
** Scrive sul canale di comunicazione se l'operazione è andata a buon fine oppure no.
** (Inoltre riempie la struttura cl_t relativa al cliente corrente, in modo da
** accedervi successivamente senza dover rileggere la lista dei client.)
** @param: -name: il nome dell'utente da registrare.
** -conn: è il descrittore del canale di comunicazione.
** -data_path: è il path della directory nella quale cercare o creare "name".
** (-l: è la lista che contiene tutti i clienti.)
** -c: è il puntatore alla struttura dati del cliente attuale.
** @return: 1 se è andata a buon fine, 0 altrimenti.
*/
int s_connect(long conn, char* data_path, /*list_t* l, */char* name, cl_t* c);
/*
** Salva un nuovo file all'interno della cartella dell'utente corrente,
** con nome "name", solo se questo nome non è già esistente. Il file è
** riempito con blocco dati "block" di grandezza "len". Scrive sul canale
** di comunicazione se l'operazione è andata a buon fine oppure no.
** @param: -name: il nome del nuovo file.
** -conn: è il descrittore del canale di comunicazione.
** -block: i dati da inserire nel file.
** -len: la lunghezza dei dati.
** -cl_path: il path dove andare a creare il nuovo file.
** @return: 1 se è andata a buon fine, 0 altrimenti.
*/
int s_store(long conn, char* name, void* block, size_t len, char* cl_path);
/*
** Recupera il blocco dati con nome "name". Invia sul canale di comunicazione
** il blocco se è stato trovato oppure un messaggio d'errore.
** @param: -name: il nome del file da cercare.
** -conn: è il descrittore del canale di comunicazione.
** -cl_path: il path dove cercare il file.
** @return: 1 se è andata a buon fine, 0 altrimenti.
*/
int s_retrieve(long conn, char* name, char* cl_path);
/*
** Elimina il file con nome "name" se esiste. Scrive sul canale di comunicazione
** se l'operazione è andata a buon fine oppure no.
** @param: -name: il nome del file da eliminare.
** -conn: è il descrittore del canale di comunicazione.
** -cl_path: il path dove si trova il file da eliminare.
** @return: ritorna la size del file eliminato.
*/
int s_delete(long conn, char* name, char* cl_path);
/*
** Chiude la connessione con il client. Scrive sul canale di comunicazione
** l'andata a buon fine.
** @param: -conn: è il descrittore del canale di comunicazione.
*/
void s_leave(long conn);
/*
** Questa funzione stampa il contenuto della struttura s che contiene le statistiche.
** @param: -s: è la struttura che contiene le statistiche.
*/
void print_stat(st_t s);
#endif
|
import React from "react";
const ShowSelectedFile = ({ images, handleDelete }) => {
return (
<div className="container-fluid mt-5">
{images && images.length > 0 && (
<div class="relative overflow-x-auto shadow-md sm:rounded-lg">
<table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
<thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
<th scope="col" class="px-6 py-3">
<span class="sr-only">Image</span>
Images
</th>
<th scope="col" class="px-6 py-3">
Name
</th>
<th scope="col" class="px-6 py-3">
Action
</th>
</tr>
</thead>
<tbody>
{images.map((item, index) => {
return (
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600">
<td class="w-1/2 h-1/3 p-4">
<img src={URL.createObjectURL(item)} alt="Apple Watch" />
</td>
<td class="px-6 py-4 font-semibold text-gray-900 dark:text-white">
{item.name}
</td>
<td class="px-6 py-4">
{/* <a
class="font-medium text-red-600 dark:text-red-500 hover:underline"
>
Red
</a> */}
<button
onClick={() => handleDelete(index)}
type="button"
class="text-white bg-gradient-to-r from-red-400 via-red-500 to-red-600 hover:bg-gradient-to-br focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 shadow-lg shadow-red-500/50 dark:shadow-lg dark:shadow-red-800/80 font-medium rounded-lg text-sm px-5 py-2.5 text-center mr-2 mb-2"
>
Remove
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
};
export default ShowSelectedFile;
|
import re
class Solution:
''' Using regex to format string '''
def isPalindrome(self, s: str) -> bool:
formatted_str = re.sub('[^A-Za-z0-9]+', '', s)
formatted_str = formatted_str.lower()
return formatted_str[::-1] == formatted_str
s = 'race a car'
solution = Solution()
result = solution.isPalindrome(s)
print(result)
class Solution2:
''' Using isalnum() '''
def isPalindrome(self, s: str) -> bool:
new_s = ''.join(e for e in s if e.isalnum()).lower()
return new_s[::-1] == new_s
s = 'race a car'
solution = Solution2()
result = solution.isPalindrome(s)
print(result)
''' In both cases, we use the new array to store the new formated string, therefore, the time complexity is O(n), space complexity is O(n)'''
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/navbar-fixed.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="img/1882.jpg" type="image/x-icon">
<title>Mezuxe</title>
</head>
<body>
<nav class="navbar navbar-light navbar-expand-lg fixed-top py-3">
<div class="container">
<a href="#shortcut" class="navbar-brand">
<img src="img/1882.jpg" class="img-fluid rounded-circle ml-auto" width="50" height="50" alt="lo">
<h3 class="d-inline align-middle">Tareq Ahsan</h3>
</a>
<button class="navbar-toggler navbar-toggler-right" data-toggle="collapse" data-target="#navi">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navi">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#authors">Meet the authors</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contract">Contract</a>
</li>
</ul>
</div>
</div>
</nav>
<!--showcase-->
<section id="shortcut" class="text-center text-light">
<div class="primary-overlay">
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-12">
<h3 class="display-1 mt-5 py-4">Do What You Dream off..</h3>
<p class="lead">lorem epsam jkwkelj kjlekjwe lkjeelkje klwejqwlke lkejqkle lkjelqkjwe lqkejqkle
</p>
<a href="#" class="btn btn-outline-light py-2">
<i class="fa fa-arrow-right"></i>Read more
</a>
</div>
<div class="col-lg-6 inner">
<img src="img/diego-ph-fIq0tET6llw-unsplash.jpg"
class="img-fluid rounded-circle d-none d-lg-block " alt="book">
</div>
</div>
</div>
</div>
</section>
<!--submit-->
<section id="submit" class="py-5">
<div class="container">
<form class="row">
<div class="col-lg-4">
<div class="form-group my-auto">
<input type="text" placeholder="Name" class="form-control form-control-lg">
</div>
</div>
<div class="col-lg-4">
<div class="form-group my-2 my-md-2 my-lg-auto">
<input type="Email" placeholder="Email" class="form-control form-control-lg">
</div>
</div>
<div class="col-lg-4">
<button class="btn btn-primary btn-block btn-lg">
<i class="fa fa-envelope-open-o"></i>Send
</button>
</div>
</form>
</div>
</section>
<!--card-->
<section id="box" class="py-3 text-center">
<div class="container">
<div class="row">
<div class="col-lg-3">
<div class="card border-primary">
<div class="card-body">
<h3 class="text-primary">Be Better</h3>
<p class="lead">lorem epsam i am tareq i have completed my bsc from daffodil international
university.
and got cgpa 3.46 and completed a project</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card border-primary bg-primary">
<div class="card-body ">
<h3>Be Smarter</h3>
<p class="lead">lorem epsam i am tareq i have completed my bsc from daffodil international
university.
and got cgpa 3.46 and completed a project</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card border-primary">
<div class="card-body">
<h3 class="text-primary">BE Faster</h3>
<p class="lead">orem epsam i am tareq i have completed my bsc from daffodil international
university.
and got cgpa 3.46 and completed a project</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card border-primary bg-primary">
<div class="card-body ">
<h3>Be Stronger</h3>
<p class="lead">orem epsam i am tareq i have completed my bsc from daffodil international
university.
and got cgpa 3.46 and completed a project</p>
</div>
</div>
</div>
</div>
</div>
</section>
<!--about-->
<section id="about" class="text-center bg-light py-5">
<div class="container">
<div class="row">
<div class="col-12">
<h3 class="display-4 text-primary">Why this Book?</h3>
<p class="lead mt-4">lorem epsam jhdjh kljsdjsd kjdlkjd kljdlkjd kljdlkjds ljkljkf lkdjlkjd lkjdalkd
kljdlkj klsdjlkj
lkdjkld ieurweru uiuior iurior iuroiur iour qrui</p>
<!--accordion-->
<div id="accordion" role="tablist" class="pt-5">
<div class="card">
<div class="card-header" role="tab">
<h5 class="mb-0">
<div data-toggle="collapse" data-target="#collone">
<i class="fa fa-arrow-circle-down"></i>
Get Inspired
</div>
</h5>
</div>
<div id="collone" class="collapse show" data-parent="#accordion">
<div class="card-body">
<p class="lead">lorem epsam jhdjh kljsdjsd kjdlkjd kljdlkjd kljdlkjds ljkljkf
lkdjlkjd lkjdalkd kljdlkj klsdjlkj
lkdjkld ieurweru uiuior iurior iuroiur hjkhre hrjkelrh jherhjeh iour qrui</p>
</div>
</div>
</div>
<div class="card" role="tablist">
<div class="card-header ">
<h5 class="mb-0">
<div data-toggle="collapse" data-target="#colltwo">
<i class="fa fa-arrow-circle-down"></i>
Gain the knowledge
</div>
</h5>
</div>
<div id="colltwo" class="collapse" data-parent="#accordion">
<div class="card-body">
<p class="lead">lorem epsam jhdjh kljsdjsd kjdlkjd kljdlkjd kljdlkjds ljkljkf
lkdjlkjd lkjdalkd kljdlkj klsdjlkj
lkdjkld ieurweru uiuior iurior iuroiur hjkhre hrjkelrh jherhjeh iour qrui</p>
</div>
</div>
</div>
<div class="card" role="tablist">
<div class="card-header">
<h5 class="mb-0">
<div data-toggle="collapse" data-target="#collthree">
<i class="fa fa-arrow-circle-down"></i>
Open your mind
</div>
</h5>
</div>
<div id="collthree" class="collapse" data-parent="#accordion">
<div class="card-body">
<p class="lead">lorem epsam jhdjh kljsdjsd kjdlkjd kljdlkjd kljdlkjds ljkljkf
lkdjlkjd lkjdalkd kljdlkj klsdjlkj lkdjkld ieurweru uiuior iurior iuroiur hjkhre
hrjkelrh jherhjeh iour qrui</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--authors-->
<section id="authors" class="text-center py-5">
<div class="container">
<div class="row">
<div class="col-12">
<div class="info-authors mb-5">
<h2 class="display-4 text-primary">Meet the authors</h2>
<p class="lead">lorem epsam jhdjh kljsdjsd kjdlkjd kljdlkjd kljdlkjds ljkljkf
lkdjlkjd lkjdalkd kljdlkj klsdjlkj lkdjkld ieurweru uiuior iurior iuroiur hjkhre
hrjkelrh jherhjeh iour qrui</p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<div class="card">
<div class="card-body">
<img src="img/a.jpg" class="img-fluid w-50 rounded-circle mb-3" alt="Tareq1">
<h3>Tareq Ahsan</h3>
<h5>Engineer</h5>
<p class="lead">orem epsam i am tareq i have completed my bsc from daffodil international
university. and got cgpa 3.46 and completed a project</p>
<div class="d-flex flex-row justify-content-center">
<div class="p-4">
<a href="https://www.facebook.com/tareq.ahsan.92">
<i class="fa fa-facebook"></i></a>
</div>
<div class="p-4">
<a href="">
<i class="fa fa-instagram"></i>
</a>
</div>
<div class="p-4">
<a href=""><i class="fa fa-linkedin">
</i></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div class="card-body">
<img src="img/b.jpg" class="img-fluid w-50 rounded-circle mb-3" alt="Ahsan">
<h3>Abid</h3>
<h5>Web designer</h5>
<p class="lead">orem epsam i am tareq i have completed my bsc from daffodil international
university. and
got cgpa 3.46 and completed a project</p>
<div class="d-flex flex-row justify-content-center">
<div class="p-4">
<a href="https://www.facebook.com/tareq.ahsan.92"><i class="fa fa-facebook">
</i></a>
</div>
<div class="p-4">
<a href="https://www.facebook.com/tareq.ahsan.92">
<i class="fa fa-instagram"></i></a>
</div>
<div class="p-4">
<a href=""> <i class="fa fa-linkedin"></i></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div class="card-body">
<img src="img/tarreq.jpg" class="img-fluid rounded-circle w-50 mb-auto" alt="tareq">
<h3>Barshan</h3>
<h5>Android Developer</h5>
<p class="lead"> i am tareq . i have work on java and java script . And i have knowledge on
html css bootstrap. Exp work on react js.done some pr </p>
<div class="d-flex flex-row justify-content-center">
<div class="p-4">
<a href="https://www.facebook.com/tareq.ahsan.92">
<i class="fa fa-facebook"></i></a>
</div>
<div class="p-4">
<a href="">
<i class="fa fa-instagram"></i>
</a>
</div>
<div class="p-4">
<a href=""><i class="fa fa-linkedin">
</i></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div class="card-body">
<img src="img/d.jpg" class="img-fluid rounded-circle w-50 mb-3 " alt="alternative">
<h3>Labib</h3>
<h5>web Developer</h5>
<p class="lead"> i am tareq . i have work on java and java script . And i have knowledge on
html css bootstrap. Exp work on react js.done some </p>
<div class="d-flex flex-row justify-content-center">
<div class="p-4">
<a href="https://www.facebook.com/tareq.ahsan.92">
<i class="fa fa-facebook"></i></a>
</div>
<div class="p-4">
<a href="">
<i class="fa fa-instagram"></i>
</a>
</div>
<div class="p-4">
<a href=""><i class="fa fa-linkedin">
</i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--footer-->
<section id="contract" class="bg-light py-4">
<div class="container">
<div class="row">
<div class="col-lg-9">
<div class="contract-info">
<h2 class="display-4"> Get In touch</h2>
<p class="lead">lorem epsam jkwkelj kjlekjwe lkjeelkje klwejqwlke lkejqkle lkjelqkjwe lqkejqkle
</p>
</div>
<form>
<div class="form-group">
<div class="input-group input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-user"></i>
</span>
</div>
<input type="text" placeholder="Name" class="form-control form-control-lg">
</div>
</div>
<div class="form-group">
<div class="input-group input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-envelope">
</i>
</span>
</div>
<input type="email" placeholder="E-mail" class="form-control form-control-lg">
</div>
</div>
<div class="form-group">
<div class="input-group input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-pencil"></i>
</span>
</div>
<textarea name="message" id="" rows="5" class="form-control form-control-lg">
</textarea>
</div>
</div>
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Submit">
</form>
</div>
<div class="col align-self-center">
<img src="img/1882.jpg" alt="logo" class="img-fluid rounded-circle d-none d-lg-block">
</div>
</div>
</div>
</section>
<!--designed by-->
<section id="footer-main" class="bg-primary py-5 text-center">
<div class="container">
<div class="row">
<div class="col-12">
<p>Copyright 2018 Ahsan</p>
<span>Designed by: <a class="text-light" href="https://www.facebook.com/tareq.ahsan.92">Tareq</a>
</span>
</div>
</div>
</div>
</section>
<script src="js/jquery.min.js"></script>
<script src="js/popper.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/navbar-fixed.js"></script>
</body>
</html>
|
import 'package:altaher_jewellery/core/managers/text_styles_manager.dart';
import 'package:altaher_jewellery/home/domain/entities/product_entity.dart';
import 'package:altaher_jewellery/search/presentation/blocs/search_cubit.dart';
import 'package:altaher_jewellery/search/presentation/widgets/search_rectangular_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../core/managers/size_manager.dart';
class SearchListItems extends StatelessWidget {
const SearchListItems({
super.key,
});
@override
Widget build(BuildContext context) {
return BlocBuilder<SearchCubit, SearchState>(
builder: (context, state) {
return Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Visibility(
visible: context
.select<SearchCubit, List<ProductEntity>>(
(cubit) => cubit.filteredProducts)
.isNotEmpty,
replacement: Center(
child: Text(
'عفوا هذا المنتج غير موجود.',
style: TextStyleManager.black_24ALMARAI,
),
),
child: Expanded(
child: ListView.separated(
padding: EdgeInsets.fromLTRB(
AppPadding.padding6.w,
AppPadding.padding25.h,
AppPadding.padding6.w,
AppPadding.padding16.h,
),
itemCount:
context.read<SearchCubit>().filteredProducts.length,
itemBuilder: (context, index) {
final filteredProducts =
context.read<SearchCubit>().filteredProducts;
return SearchRectangularCard(
allProducts: filteredProducts,
product: filteredProducts[index],
);
},
separatorBuilder: (BuildContext context, int index) =>
SizedBox(
height: 15.h,
),
),
),
),
],
);
},
);
}
}
|
import { useMatchMedia } from "@lilib/hooks";
import renderHook from "./helpers/renderHook";
describe("useMatchMedia", () => {
beforeAll(() => {
Object.defineProperty(window, "matchMedia", {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
})),
});
});
it("should return a boolean value", () => {
const { result } = renderHook(() => useMatchMedia("(max-width: 1000px)"));
expect(typeof result.current).toBe("boolean");
});
});
|
import React from "react";
const List = ({ key, task }) => {
return (
<li key={key} className="card-task">
<h3>{task.title}</h3>
<p>{task.description}</p>
<p>Due Date: {task.dueDate}</p>
<p>
Tags:{" "}
{Array.isArray(task.tags) ? task.tags.join(", ") : "No Tags"}
</p>
<h3>Checklists:</h3>
{task.checklists.map((item, checklistIndex) => (
<p key={checklistIndex}>
{item.isDone ? "✅" : "❌"} {item.checklistItem}
</p>
))}
<h3>Attachments:</h3>
{task.attachments.map((attachment, attachmentIndex) => (
<p key={attachmentIndex}>
<a
href={attachment.link}
target="_blank"
rel="noopener noreferrer"
>
{attachment.displayText}
</a>
</p>
))}
</li>
);
};
export default List;
|
---
author: "nao.deng"
title: "gatling 性能测试教程:入门介绍"
date: "2023-10-24T17:44:53+08:00"
summary: "文章介绍性能测试工具 gatling 的新手入门介绍,环境搭建,如何将官方 demo 跑起来"
ZHtags: [
"入门介绍","环境搭建"]
ZHcategories: ["性能测试", "Gatling"]
ZHseries: ["Gatling 性能测试教程"]
ShowWordCount: true
---
## Gatling 介绍
Gatling 是一个用于性能测试和负载测试的开源工具,特别适用于测试 Web 应用程序。它是一个基于 Scala 编程语言的高性能工具,用于模拟并测量应用程序在不同负载下的性能。
以下是 Gatling 的一些重要特点和优势:
- 基于 Scala 编程语言:Gatling 的测试脚本使用 Scala 编写,这使得它具有强大的编程能力,允许用户编写复杂的测试场景和逻辑。
- 高性能:Gatling 被设计为高性能的负载测试工具。它使用了非阻塞的 I/O 和异步编程模型,能够模拟大量并发用户,从而更好地模拟真实世界中的负载情况。
- 易于学习和使用:尽管 Gatling 的测试脚本是使用 Scala 编写的,但它的 DSL(领域特定语言)非常简单,容易上手。即使你不熟悉 Scala,也可以快速学会如何创建测试脚本。
- 丰富的功能:Gatling 提供了丰富的功能,包括请求和响应处理、数据提取、条件断言、性能报告生成等。这些功能使你能够创建复杂的测试场景,并对应用程序的性能进行全面的评估。
- 多协议支持:除了 HTTP 和 HTTPS,Gatling 还支持其他协议,如 WebSocket,JMS,和 SMTP。这使得它适用于测试各种不同类型的应用程序。
- 实时结果分析:Gatling 可以在测试运行期间提供实时的性能数据和图形化报告,帮助你快速发现性能问题。
- 开源和活跃的社区:Gatling 是一个开源项目,拥有一个活跃的社区,不断更新和改进工具。
- 支持 CI/CD 集成:Gatling 可以与 CI/CD 工具(如 Jenkins)集成,以便在持续集成和持续交付流程中执行性能测试。
总的来说,Gatling 是一个功能强大的性能测试工具,适用于测试各种类型的应用程序,帮助开发团队识别和解决性能问题,以确保应用程序在生产环境中具有稳定的性能和可伸缩性。
## 环境搭建
> 由于我是 macbook,后面的介绍几本会以 macbook demo 为例,windows 的同学可以自行参考
### VSCode + Gradle + Scala 版本
#### 准备工作
- [x] 开发工具:VSCode
- [x] 安装 Gradle 版本>=6.0,我使用的 Gradle 8.44
- [x] 安装 JDK 版本>=8,我使用的 JDK 19
#### 安装插件
- [x] VSCode 搜索 Scala (Metals) 插件进行安装
- [x] VSCode 搜索 Gradle for Java 插件进行安装
#### 官方 demo 初始化&调试
> 前面先会用官方 demo 工程来做初始化和调试,后面再介绍如何自己创建工程
- 克隆官方 demo 工程
```bash
git clone git@github.com:gatling/gatling-gradle-plugin-demo-scala.git
```
- 使用 VSCode 打开克隆下来的官方 demo 工程
- 用 VSCode 打开本项目 Terminal 窗口,执行以下命令
```bash
gradle build
```

- 运行工程中的 demo
```bash
gradle gatlingRun
```
- 查看命令行运行结果

- 点击命令行报告中的 html 报告链接,并使用浏览器打开,即可查看详细的报告信息

### VSCode + Maven + Scala 版本
#### 准备工作
- [x] 开发工具:VSCode
- [x] 安装 Maven,我使用的 Maven 3.9.5
- [x] JDK 版本>=8,我使用的 JDK 19
#### 安装插件
- [x] VSCode 搜索 Scala (Metals) 插件进行安装
- [x] VSCode 搜索 Maven for Java 插件进行安装
#### 官方 demo 初始化&调试
> 前面先会用官方 demo 工程来做初始化和调试,后面再介绍如何自己创建工程
- 克隆官方 demo 工程
```bash
git clone git@github.com:gatling/gatling-maven-plugin-demo-scala.git
```
- 使用 VSCode 打开克隆下来的官方 demo 工程
- 用 VSCode 打开本项目 Terminal 窗口,执行以下命令运行工程中的 demo
```bash
mvn gatling:test
```
- 查看命令行运行结果

- 点击命令行报告中的 html 报告链接,并使用浏览器打开,即可查看详细的报告信息

### IDEA + Gradle + Scala 版本
与 VSCode 下基本类似,这里就不再赘述了
差异点如下:
- IDEA 搜索 Scala 插件进行安装
- 新的运行方式:右键选择项目目录下的 Engine.scala 文件,选择 Run 'Engine'也可以运行 demo(运行过程中需要按回车键确认哦)
### IDEA + Maven + Scala 版本
与 VSCode 下基本类似,这里就不再赘述了
差异点如下:
- IDEA 搜索 Scala 插件进行安装
- 新的运行方式:右键选择项目目录下的 Engine.scala 文件,选择 Run 'Engine'也可以运行 demo(运行过程中需要按回车键确认哦)
---
欢迎关注软件测试同学的公众号“**软件测试同学**”,原创 QA 技术文章第一时间推送。
<!-- markdownlint-disable MD045 -->
<!-- markdownlint-disable MD033 -->
<center>
<img src="https://cdn.jsdelivr.net/gh/naodeng/blogimg@master/uPic/2023112015'QR Code for 公众号.jpg" style="width: 100px;">
</center>
<!-- markdownlint-disable MD033 -->
<!-- markdownlint-disable MD045 -->
|
package com.example.login.repository;
import static org.assertj.core.api.Assertions.assertThat;
import com.example.login.model.Account;
import com.example.login.model.AccountType;
import com.example.login.model.ConfirmationToken;
import com.example.login.model.User;
import com.example.login.model.UserGroup;
import com.example.login.model.UserRole;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ConfirmationTokenRepositoryTest {
@Autowired
ConfirmationTokenRepository confirmationTokenRepository;
@Autowired
AccountRepository accountRepository;
@Autowired
UserRepository userRepository;
@Autowired
UserGroupRepository userGroupRepository;
User user = new User(), user1 = new User();
Account account = new Account();
UserGroup userGroup = new UserGroup(), userGroup1 = new UserGroup(), userGroup2 = new UserGroup();
ConfirmationToken confirmationToken = new ConfirmationToken();
@AfterEach
void tearDown() {
account = null;
user = user1 = null;
userGroup = userGroup1 = userGroup2 = null;
confirmationToken = null;
}
@BeforeEach
void setUp() {
userGroup.setGroupName("Group 1");
userGroup1.setGroupName("Group 2");
userGroup2.setGroupName("Group 3");
Set<UserGroup> group1 = new HashSet<>();
group1.add(userGroup);
group1.add(userGroup2);
Set<UserGroup> group2 = new HashSet<>();
group2.add(userGroup1);
group2.add(userGroup2);
account.setAccountType(AccountType.BASIC);
account.setName("Name");
account.setDescription("Description");
user.setUserType(UserRole.USER);
user.setIsAdmin("y");
user.setContactEmail("abc@gmail.com");
user.setScreenName("Abc");
user.setName("Name");
user.setDescription("Description");
user.setAccountId(account);
user.setUserGroups(group1);
user1.setUserType(UserRole.ADMIN);
user1.setIsAdmin("n");
user1.setContactEmail("asdf@gmail.com");
user1.setScreenName("Asdf");
user1.setName("Name");
user1.setDescription("Description");
user1.setAccountId(account);
user1.setUserGroups(group2);
confirmationToken.setToken(UUID.randomUUID().toString());
confirmationToken.setCreatedAt(LocalDateTime.now());
confirmationToken.setExpiresAt(LocalDateTime.now().plusMinutes(15));
confirmationToken.setUserId(user);
}
@Test
void findByToken() {
accountRepository.save(account);
userGroupRepository.save(userGroup);
userRepository.save(user);
confirmationTokenRepository.save(confirmationToken);
ConfirmationToken fetchConfirmationToken = null;
if (confirmationTokenRepository.existsConfirmationTokenByToken(confirmationToken.getToken())) {
fetchConfirmationToken = confirmationTokenRepository.findByToken(
confirmationToken.getToken());
}
assertThat(fetchConfirmationToken.getToken()).isEqualTo(confirmationToken.getToken());
}
@Test
void existsConfirmationTokenByToken() {
accountRepository.save(account);
userGroupRepository.save(userGroup);
userRepository.save(user);
confirmationTokenRepository.save(confirmationToken);
boolean confirmationTokenExists = confirmationTokenRepository.existsConfirmationTokenByToken(
confirmationToken.getToken());
assertThat(confirmationTokenExists).isEqualTo(true);
}
@Test
void updateConfirmedAt() {
accountRepository.save(account);
userGroupRepository.save(userGroup);
userRepository.save(user);
confirmationTokenRepository.save(confirmationToken);
if (confirmationTokenRepository.existsConfirmationTokenByToken(confirmationToken.getToken())) {
confirmationTokenRepository.updateConfirmedAt(confirmationToken.getToken(),
LocalDateTime.now());
}
ConfirmationToken fetchConfirmationToken = null;
if (confirmationTokenRepository.existsConfirmationTokenByToken(confirmationToken.getToken())) {
fetchConfirmationToken = confirmationTokenRepository.findByToken(
confirmationToken.getToken());
}
assertThat(fetchConfirmationToken.getConfirmedAt()).isEqualTo(
confirmationToken.getConfirmedAt());
}
}
|
package techproedenglish01.techproedenglish01api;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
public class GetRequest06 {
/*
When I send a GET request to REST API URL
http://dummy.restapiexample.com/api/v1/employees
And Accept type is “application/JSON”
Then
HTTP Status Code should be 200
And Response format should be "application/JSON"
And there should be 24 employees
And "Ashton Cox" should be one of the employees
And 21, 61, and 23 should be among the employee ages
*/
@Test
public void get01() {
Response response = given().accept(ContentType.JSON).when().get("http://dummy.restapiexample.com/api/v1/employees");
response.prettyPrint();
response.
then().
assertThat().
statusCode(200).
contentType(ContentType.JSON).
body("data.id", hasSize(24),// And there should be 24 employees
"data.employee_name", hasItem("Ashton Cox"),//Single data için
"data.employee_age", hasItems("21", "23", "61"));//Multiple data için
}
}
|
import React, { Component } from 'react';
import Card, { CardContent } from 'material-ui/Card';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
import Typography from 'material-ui/Typography';
import axios from 'axios';
class LaunchPadStats extends Component {
constructor(props) {
super(props);
this.state = {
stats: {},
location: {},
vehicles: []
};
}
componentDidMount() {
this.getLaunchPadStats();
}
getLaunchPadStats() {
axios
.get(`https://api.spacexdata.com/v2/launchpads/${this.props.launchpad}`)
.then(res => this.setState(
{
stats: res.data,
location: res.data.location,
vehicles: res.data.vehicles_launched
}
))
.catch(err => console.log(err));
}
render() {
const MapComponent = withScriptjs(withGoogleMap((props) =>
<GoogleMap defaultZoom={8} defaultCenter={{ lat: props.lat, lng: props.lng }}>
{props.isMarkerShown && <Marker position={{ lat: props.lat, lng: props.lng }} />}
</GoogleMap>
))
return (
<div>
<Card>
<CardContent>
<Typography variant="headline" component="h3">
{this.state.stats.full_name} ({this.state.stats.id})
</Typography>
<p>
<strong>Status</strong>: {this.state.stats.status}
</p>
<p>
{this.state.stats.details}
</p>
<p>
<strong>Location</strong>:
</p>
<ul>
<li>{this.state.location.name}</li>
<li>{this.state.location.region}</li>
<li>{this.state.location.latitude}</li>
<li>{this.state.location.longitude}</li>
</ul>
<strong>Vehicles Launched</strong>:
<ul>
{this.state.vehicles.map(vehicle =>
<li key={vehicle}>
{vehicle}
</li>
)}
</ul>
<MapComponent
isMarkerShown
lat={this.state.location.latitude}
lng={this.state.location.longitude}
googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyDwXeOkvrpyz9dgOZpsB5ahygjdB43Kj2g&v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</CardContent>
</Card>
</div>
);
}
}
export default LaunchPadStats;
|
import { useState, useEffect } from 'react';
import Spinner from '../components/Spinner';
import ContactForm from '../components/ContactForm';
import { mongooseConnect } from '../lib/mongoose';
import { useRouter } from 'next/router';
import CategoryModel from '../models/Category';
import { NextSeo } from 'next-seo';
const ContactPage = () => {
const [loading, setLoading] = useState(true);
useEffect(() => {
setTimeout(() => {
setLoading(false);
}, 2000);
}, []);
return (
<>
<NextSeo
title='Kontaktai'
description='Kontaktai'
openGraph={{
type: 'website',
locale: 'en_IE',
url: 'https://yourwebsite.com/',
site_name: 'Vandens Talpos',
images: [
{
url: 'https://res.cloudinary.com/dtv9ufmel/image/upload/v1712755967/ecommerce-app/nkdyueoqvtwbc215unry.png',
width: 1200,
height: 630,
alt: 'Roto image',
},
],
}}
twitter={{
handle: '@handle',
site: '@site',
cardType: 'summary_large_image',
}}
/>
<div className='container mx-auto mt-8'>
{loading ? (
<div className='flex justify-center items-center min-h-screen'>
<Spinner />
</div>
) : (
<>
<ContactForm />
</>
)}
</div>
</>
);
};
export default ContactPage;
export async function getServerSideProps() {
await mongooseConnect();
let categories = [];
try {
categories = await CategoryModel.find().lean().exec();
categories = categories.map((category) => ({
...category,
_id: category._id.toString(),
parent: category.parent ? category.parent.toString() : null,
}));
} catch (error) {
console.error('Error fetching categories:', error);
}
return {
props: {
categories,
},
};
}
|
import { FC, useState, useContext } from "react";
import { Context } from "../../index";
import { Button, Input } from "@mui/material";
import { Link } from "react-router-dom";
import { observer } from "mobx-react-lite";
import Title from "../../components/Title/Title";
import "./registrationForm.sass";
const RegistrationForm: FC = () => {
const [email, setEmail] = useState<string>("");
const [username, setUsername] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [firstName, setFirstName] = useState<string>("");
const [lastName, setLastName] = useState<string>("");
const { store } = useContext(Context);
const inputStyles = {
margin: "1.5rem 1.3rem 0.8rem 1.3rem",
":after": { borderBottom: "2px solid #534ED9" },
};
const btnStyles = {
margin: "2rem 1.3rem 2rem 1.3rem",
backgroundColor: "#534ED9",
":hover": { backgroundColor: "#7673D9" },
};
return (
<form className="registr__form">
<div className="title__box">
<Title />
</div>
<div className="form__box">
<h2 className="form__h2">Join Us</h2>
<p className="error">{store.error}</p>
<Input
placeholder="Email"
type="text"
sx={inputStyles}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<Input
placeholder="Username"
type="text"
sx={inputStyles}
onChange={(e) => {
setUsername(e.target.value);
}}
/>
<Input
placeholder="First Name"
type="text"
sx={inputStyles}
onChange={(e) => {
setFirstName(e.target.value);
}}
/>
<Input
placeholder="Last Name"
type="text"
sx={inputStyles}
onChange={(e) => {
setLastName(e.target.value);
}}
/>
<Input
autoComplete="on"
placeholder="Password"
type="password"
sx={inputStyles}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<Button
variant="contained"
sx={btnStyles}
onClick={async () => {
await store.registration(
email,
username,
password,
firstName,
lastName
);
store.checkAuth();
}}
>
Sign Up
</Button>
<div className="form__linkBox">
<span>Have an account?</span>
<Link to="/login" className="signIn">
Sign In
</Link>
</div>
</div>
</form>
);
};
export default observer(RegistrationForm);
|
package main
import (
"container/heap"
)
func main() {
// Some items and their priorities.
// items := map[string]int{
// "banana": 3, "apple": 2, "pear": 4,
// }
// Create a priority queue, put the items in it, and
// establish the priority queue (heap) invariants.
pq := make(PriorityQueue, 0)
// i := 0
// for value, priority := range items {
// pq[i] = &Item{
// value: value,
// priority: priority,
// index: i,
// }
// i++
// }
heap.Init(&pq)
// Insert a new item and then modify its priority.
item := &Item{
value: 1,
priority: 1,
}
heap.Push(&pq, item)
pq.update(item, item.value, 5)
// i := heap.Pop(&pq)
// fmt.Print(*i.value)
// Take the items out; they arrive in decreasing priority order.
// for pq.Len() > 0 {
// item := heap.Pop(&pq).(*Item)
// fmt.Printf("%.2d:%s ", item.priority, item.value)
// }
// Output:
// 05:orange 04:pear 03:banana 02:apple
}
// An Item is something we manage in a priority queue.
type Item struct {
value int // The value of the item; arbitrary.
priority int // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
return pq[i].priority > pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value int, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}
// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
// func Example_priorityQueue() {
// }
type LFUCache struct {
len int
hnode PriorityQueue
}
func Constructor(capacity int) LFUCache {
}
func (this *LFUCache) Get(key int) int {
}
func (this *LFUCache) Put(key int, value int) {
}
|
package it.l_soft.contacto.rest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
public class ApplicationProperties {
// parameters from the call
private int languageId = 1;
// package properties
private int sessionExpireTime = 0;
private String defaultLang = "";
private boolean useCoars = false;
// env specific
private String mailSmtpHost = "";
private String mailUser = "";
private String mailPassword = "";
private ServletContext context;
private static ApplicationProperties instance = null;
final Logger log = Logger.getLogger(this.getClass());
public static ApplicationProperties getInstance()
{
if (instance == null)
{
instance = new ApplicationProperties();
}
return(instance);
}
private ApplicationProperties()
{
String variable = "";
log.trace("ApplicationProperties start");
Properties properties = new Properties();
log.debug("path of abs / '" + ApplicationProperties.class.getResource("/").getPath() + "'");
try
{
log.debug("path of abs package.properties '" +
ApplicationProperties.class.getResource("/resources/package.properties").getPath() + "'");
InputStream in = ApplicationProperties.class.getResourceAsStream("/resources/package.properties");
if (in == null)
{
log.error("resource path not found");
return;
}
properties.load(in);
in.close();
}
catch(IOException e)
{
log.warn("Exception " + e.getMessage(), e);
return;
}
defaultLang = properties.getProperty("defaultLang");
useCoars = Boolean.parseBoolean(properties.getProperty("useCoars"));
try
{
variable = "sessionExpireTime";
sessionExpireTime = Integer.parseInt(properties.getProperty("sessionExpireTime"));
}
catch(NumberFormatException e)
{
log.error("The format for the variable '" + variable + "' is incorrect (" +
properties.getProperty("sessionExpireTime") + ")", e);
}
String envConf = System.getProperty("envConf");
try
{
properties = new Properties();
String siteProps = "/resources/env." + (envConf == null ? "dev" : envConf) + ".properties";
log.debug("using '" + siteProps + "' at '" + ApplicationProperties.class.getResource(siteProps).getPath() + "'");
InputStream in = ApplicationProperties.class.getResourceAsStream(siteProps);
properties.load(in);
in.close();
}
catch(IOException e)
{
log.error("Exception " + e.getMessage(), e);
return;
}
mailSmtpHost = properties.getProperty("mailSmtpHost");
mailUser = properties.getProperty("mailUser");
mailPassword = properties.getProperty("mailPassword");
}
public String getMailSmtpHost() {
return mailSmtpHost;
}
public String getMailUser() {
return mailUser;
}
public String getMailPassword() {
return mailPassword;
}
public int getSessionExpireTime() {
return sessionExpireTime;
}
public String getDefaultLang() {
return defaultLang;
}
public boolean isUseCoars() {
return useCoars;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(String languageId) {
// this.languageId = languageId;
}
}
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './main.scss'
import PokeCard from '../poke-card'
const Main = () => {
const [data, setData] = useState([]);
useEffect(() => {
const randomOffset = Math.random() * (200 - 1) + 1;
const fetchData = async () => {
const result = await axios(
`https://pokeapi.co/api/v2/pokemon?limit=10&offset=${randomOffset}`,
);
setData(result.data.results);
};
fetchData();
}, []);
return (
<div className="content">
{
data.map(item => (
<PokeCard key={item.url} pokeUrl={item.url}></PokeCard>
))
}
</div>
);
};
export default Main;
|
'use client'
import React, { useState, useEffect } from 'react';
import ReminderCard from '../components/reminders-card';
interface Reminder {
id: number;
text: string;
completed: boolean;
}
const RemindersPage: React.FC = () => {
const [reminders, setReminders] = useState<Reminder[]>([]);
useEffect(() => {
// Fetch the reminders data from the JSON file
async function fetchReminders() {
try {
const response = await fetch('/reminders.json');
const data = await response.json();
setReminders(data);
} catch (error) {
console.error('Error fetching reminders:', error);
}
}
fetchReminders();
}, []);
const handleReminderClick = (id: number) => {
setReminders((prevReminders) =>
prevReminders.map((reminder) =>
reminder.id === id ? { ...reminder, completed: !reminder.completed } : reminder
)
);
};
const handleNewClick = () => {
// Create a new reminder with a unique ID and initial properties
const newReminder: Reminder = {
id: reminders.length + 1, // Assign a unique ID (you may need to adjust this logic as needed)
text: 'New Reminder', // Set the initial text for the new reminder
completed: false, // Set the initial completed status for the new reminder
};
// Add the new reminder to the array
setReminders((prevReminders) => [...prevReminders, newReminder]);
};
const handleRemoveClick = (id: number) => {
// Filter out the reminder with the specified ID to remove it
setReminders((prevReminders) => prevReminders.filter((reminder) => reminder.id !== id));
};
const handleInputChange = (id: number, newValue: string) => {
setReminders((prevReminders) =>
prevReminders.map((reminder) =>
reminder.id === id ? { ...reminder, text: newValue } : reminder
)
);
};
return (
<div className={'card border p-8 drop-shadow-md rounded mb-4 bg-white flex flex-col w-screen'}>
<ReminderCard
reminders={reminders}
onReminderClick={handleReminderClick}
onNewClick={handleNewClick}
onRemoveClick={handleRemoveClick}
onInputChange={handleInputChange}
/>
</div>
);
};
export default RemindersPage;
|
import { useParams, Link } from 'react-router-dom'
import { connect, useSelector } from 'react-redux'
import { Formik, Form } from 'formik'
import { reset_password_confirm } from '../../actions/authActions'
import { validateNewPassword } from '../../validators/validators'
import { Loader, Message } from '../../components/basics'
import { TextField } from '../../components/formHelpers'
import LayoutAuth from '../../hocs/LayoutAuth'
import Background from '../../images/resetpass.jpg'
import { VscCheckAll } from 'react-icons/vsc'
import styles from '../../components/company/CompanyProfileForm.module.css'
const ResetPasswordConfirm = ({ reset_password_confirm }) => {
const uid = useParams().uid
const token = useParams().token
const auth = useSelector((state) => state.auth)
const { error, loading, success } = auth
return (
<LayoutAuth bgImage={Background}>
<h3 className='display-4'>Podaj nowe hasło</h3>
{error && <Message variant='danger'>{error}</Message>}
{loading && <Loader />}
{success && (
<Message variant='success'>
Pomyślnie zmieniono hasło <VscCheckAll />
</Message>
)}
<p className='text-muted mb-4'>
Po zatwierdzeniu nowego hasła, użyj go do zalogowania się do swojego
konta.
</p>
<Formik
initialValues={{
new_password: '',
re_new_password: '',
}}
validationSchema={validateNewPassword}
onSubmit={(values, { resetForm }) => {
const { new_password, re_new_password } = values
reset_password_confirm(uid, token, new_password, re_new_password)
resetForm({ values: '' })
}}
>
{({ values }) => (
<Form>
<TextField label='Hasło' name='new_password' type='password' />
<TextField
label='Potwierdź hasło'
name='re_new_password'
type='password'
/>
<button className={styles['yellow-blck-btn']} type='submit'>
Zmień hasło
</button>
</Form>
)}
</Formik>
<p className='mt-3'>
Hasło zostało zmienione?{' '}
<Link className='text-decoration-none' to='/logowanie'>
Zaloguj się
</Link>
</p>
</LayoutAuth>
)
}
export default connect(null, { reset_password_confirm })(ResetPasswordConfirm)
|
<script>
import { onMount } from 'svelte';
import { ToDoService } from '../services/todo.service';
import ToDoItem from './ToDoItem.svelte';
let isReady = false,
isLoading = false,
todos = [],
newText = '',
inputEl;
onMount(async () => {
try {
todos = await ToDoService.getAll();
} catch (error) {
console.error(error);
} finally {
isReady = true;
}
});
async function handleSubmit(e) {
if (newText.length === 0) {
return;
}
isLoading = true;
try {
const newToDo = await ToDoService.add(newText);
todos = [...todos, newToDo];
newText = '';
setTimeout(function() {
inputEl.focus(); // Fix for Chrome-based browsers. Engine is too fast without setTimeout
}, 1);
} catch (error) {
console.error(error);
} finally {
isLoading = false;
}
}
async function handleDelete(event) {
try {
const { detail: todoId } = event;
await ToDoService.delete(todoId);
todos = todos.filter(td => td.id !== todoId);
} catch (error) {
console.error(error);
}
}
async function handleEdit(event) {
try {
const { detail: todo } = event;
await ToDoService.update(todo);
todos = todos.map(td => {
if (td.id !== todo.id) {
return td;
}
return { ...td, ...todo };
});
} catch (error) {
console.error(error);
}
}
</script>
<style lang="scss">
.todo-list {
&-header {
text-align: center;
}
&-collection {
border: 1px solid #b6b5b6;
border-radius: 4px;
box-shadow: 2px 2px 5px 0 #aaa;
}
&-entry {
margin-bottom: .75rem;
}
}
</style>
<section class="todo-list-container">
<h1 class="todo-list-header">ToDo List</h1>
{#if !isReady}
<h2 class="todo-list-header">Loading ToDo List...</h2>
{/if}
{#if isReady}
<form on:submit|preventDefault="{handleSubmit}">
<input class="todo-list-entry"
bind:value="{newText}"
bind:this="{inputEl}"
type="text"
maxlength="250"
placeholder="Type a ToDo and hit 'Enter'"
disabled="{isLoading}" />
</form>
{#if todos.length > 0}
<ul class="todo-list-collection">
{#each todos as todo}
<ToDoItem data="{todo}"
on:delete="{handleDelete}"
on:edit="{handleEdit}" />
{/each}
</ul>
{:else}
<h4 class="todo-list-header"><i>No ToDos. Add some!</i></h4>
{/if}
{/if}
</section>
|
import * as React from "react";
import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import { CustomTabPanel, a11yProps } from "../../../Components/mui/MuiStyles";
import PersonalDetails from "./PersonalDetails";
import PassowrdManage from "./PassowrdManage";
export default function ProfileTabs() {
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<Box sx={{ width: "100%" }}>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<Tabs
value={value}
onChange={handleChange}
aria-label="basic tabs example"
>
<Tab label="Personal details" {...a11yProps(0)} />
<Tab label="Change password" {...a11yProps(1)} />
</Tabs>
</Box>
<PersonalDetails value={value} />
<PassowrdManage value={value} />
<CustomTabPanel value={value} index={2}>
Item Three
</CustomTabPanel>
</Box>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.