text
stringlengths 184
4.48M
|
---|
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { publishValidation } from '_validations'
import { postsActions } from '_store'
import {
selectAuthUser,
selectCreateOneError,
selectCreateOneIsCreated,
} from '_helpers'
import { FadeInSection } from '_style'
// PUBLISH
/**
* Send a post request to the database and returns a publish form
* @returns A form.
*/
function Publish() {
const dispatch = useDispatch()
// SELECTORS
const createOneError = useSelector(selectCreateOneError)
const isCreated = useSelector(selectCreateOneIsCreated)
const authUser = useSelector(selectAuthUser)
const [image, setImage] = useState('')
// Call the publish form validation component
const formOptions = { resolver: yupResolver(publishValidation) }
// Get functions to build form with useForm() hook
const { register, handleSubmit, formState, reset } = useForm(formOptions)
const { errors, isSubmitting } = formState
// Prepare data as "formData" to use "multipart/form-data"
// as "content-type" of the header of the request
// then call the createPost function in the posts.slice file from the Store
function onSubmit(data) {
const formData = new FormData()
formData.append('image', image)
formData.append('title', data.title)
formData.append('postContent', data.postContent)
formData.append('author', authUser.userName)
return dispatch(postsActions.createPost({ formData }))
}
// Display the form
return (
<FadeInSection>
<div className="col-md-12 mt-5 form-publish">
<div className="shadow alert alert-info">
Publiez votre message - *champs obligatoires
</div>
<div className="card shadow">
<h4 className="card-header header-publish">Publication</h4>
<div className="card-body">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-group">
<label>*Titre</label>
<input
name="title"
type="text"
placeholder="Entre 3 et 30 caractères ..."
{...register('title')}
className={`form-control ${errors.title ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.title?.message}</div>
</div>
<div className="form-group">
<label>*Message</label>
<textarea
name="postContent"
type="text"
placeholder="Entre 3 et 300 caractères ..."
{...register('postContent')}
className={`form-control ${
errors.postContent ? 'is-invalid' : ''
}`}
/>
<div className="invalid-feedback">
{errors.postContent?.message}
</div>
</div>
<div className="form-group">
<label>*Image</label>
<input
name="image"
id="fileItem"
type="file"
onChange={(e) => setImage(e.target.files[0])}
className={`form-control ${errors.image ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.image?.message}</div>
</div>
<div className="form-group d-flex justify-content-center mt-4 justify-content-md-end gap-3">
<button
type="submit"
disabled={isSubmitting}
className="btn btn-primary my-3"
>
{isSubmitting && (
<span className="spinner-border spinner-border-sm mr-1"></span>
)}
Poster
</button>
<button
type="button"
className="btn btn-danger my-3"
onClick={() => reset()}
>
Effacer
</button>
</div>
{createOneError && (
<div className="alert alert-danger mt-3 mb-0">
{createOneError.message}
</div>
)}
{isCreated && (
<div className="alert alert-success mt-3 mb-0">
{isCreated.message}
</div>
)}
<p className="card-text">
Abandonner la publication?{' '}
<Link style={{ textDecoration: 'none' }} to={'/'}>
Retournez à l'accueil
</Link>
</p>
</form>
</div>
</div>
</div>
</FadeInSection>
)
}
export { Publish }
|
Node-ecommerce
E-Commerce App with REST API | MongoDB | Advanced Authentication
Overview
This is a Node.js e-commerce project that allows users to browse products, add them to their cart, and complete purchases.
Project is still under construction, supposed to end by 30 March 2024.
Stay tuned for updates.
Features
- User Authentication: Users can sign up, log in, and log out securely.
- Product Catalog: Users can view a list of products with details such as name, price, and description.
- Shopping Cart: Users can add products to their shopping cart and manage the quantities.
- Checkout Process: Users can complete purchases by entering shipping and payment information.
- Order History: Users can view their past orders.
- Admin Panel: Administrators can add, edit, and delete products.
Technologies Used
- Node.js
- Express.js
- MongoDB (with Mongoose ODM)
- JWT for authentication
Getting Started
1. Clone the repository:
```
git clone [https://github.com/your-username/node-ecommerce-project.git](https://github.com/shazaaly/node-ecommerce)
```
2. Install dependencies:
```
npm install
```
3. Set up environment variables:
- Create a `.env` file in the root directory
- Define the following variables:
```
PORT=3000
MONGODB_URI=mongodb://localhost:27017/ecommerce
SESSION_SECRET=your_session_secret
```
4. Run the application:
```
npm start
```
5. Access the application in your browser at `http://localhost:3000`
Folder Structure
- `config/`: Configuration files (e.g., database connection, authentication strategies).
- `models/`: Mongoose models for database schema.
- `routes/`: Express routes for different parts of the application.
- `views/`: Handlebars templates for rendering HTML.
- `public/`: Static assets (e.g., CSS, JavaScript).
- `controllers/`: Controllers for handling business logic.
- `middlewares/`: Custom middleware functions.
- `utils/`: Utility functions.
The application is deployed on Heroku. Feel free to test the live endpoints:
- **Base URL**: `https://enigmatic-ravine-23031-1df92bd6df4a.herokuapp.com`
### Endpoints
| Method | Endpoint | Description | Parameters |
|--------|-------------------------|-----------------------------------------|---------------------|
| GET | `/api/resource` | Retrieves all resources. | N/A |
| POST | `/api/resource` | Creates a new resource. | `{ "data": "value"}`|
| GET | `/api/resource/{id}` | Retrieves a resource by ID. | N/A |
| PUT | `/api/resource/{id}` | Updates a resource by ID. | `{ "data": "new value"}`|
| DELETE | `/api/resource/{id}` | Deletes a resource by ID. | N/A |
Using the Endpoints
To use these endpoints, please ensure you have the necessary authentication tokens as many operations are protected. The tokens are obtained after successfully logging in.
markdown
## Authentication
To perform operations such as creating categories, adding to cart, creating orders, or creating coupons, you must be authenticated. Use the `POST /api/auth/login` endpoint to log in and obtain your Bearer token.
Here's an example of using the `POST /api/category` endpoint to create a new category:
```http
POST /api/category
Authorization: Bearer <your-token>
Content-Type: application/json
{
"name": "Electronics",
"description": "A category for all electronic products"
}
On successful creation, you'll receive a response like:
json
{
"id": "new-category-id",
"name": "Electronics",
"description": "A category for all electronic products"
}
Note: Replace `<your-token>` with your actual auth token obtained after login.
---
Be sure to replace any placeholder text like `<your-token>` with actual valid tokens or parameters fo
For more details on how to use these endpoints, please refer to the [API Documentation] - #will be added soon
POSTMAN Doc.
https://documenter.getpostman.com/view/10270559/2sA35G4hMc
Contributing
Contributions are welcome!
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
<%@ page import="ru.moneyshark.Balance" %>
<!doctype html>
<html>
<head>
<meta name="layout" content="main">
<g:set var="entityName" value="${message(code: 'balance.label', default: 'Balance')}" />
<title><g:message code="default.show.label" args="[entityName]" /></title>
</head>
<body>
<a href="#show-balance" class="skip" tabindex="-1"><g:message code="default.link.skip.label" default="Skip to content…"/></a>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="list" action="list"><g:message code="default.list.label" args="[entityName]" /></g:link></li>
<li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
</ul>
</div>
<div id="show-balance" class="content scaffold-show" role="main">
<h1><g:message code="default.show.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<ol class="property-list balance">
<g:if test="${balanceInstance?.balance}">
<li class="fieldcontain">
<span id="balance-label" class="property-label"><g:message code="balance.balance.label" default="Balance" /></span>
<span class="property-value" aria-labelledby="balance-label"><g:fieldValue bean="${balanceInstance}" field="balance"/></span>
</li>
</g:if>
<g:if test="${balanceInstance?.comment}">
<li class="fieldcontain">
<span id="comment-label" class="property-label"><g:message code="balance.comment.label" default="Comment" /></span>
<span class="property-value" aria-labelledby="comment-label"><g:fieldValue bean="${balanceInstance}" field="comment"/></span>
</li>
</g:if>
<g:if test="${balanceInstance?.date}">
<li class="fieldcontain">
<span id="date-label" class="property-label"><g:message code="balance.date.label" default="Date" /></span>
<span class="property-value" aria-labelledby="date-label"><g:formatDate date="${balanceInstance?.date}" /></span>
</li>
</g:if>
<g:if test="${balanceInstance?.user}">
<li class="fieldcontain">
<span id="user-label" class="property-label"><g:message code="balance.user.label" default="User" /></span>
<g:each in="${balanceInstance.user}" var="u">
<span class="property-value" aria-labelledby="user-label"><g:link controller="user" action="show" id="${u.id}">${u?.encodeAsHTML()}</g:link></span>
</g:each>
</li>
</g:if>
</ol>
<g:form>
<fieldset class="buttons">
<g:hiddenField name="id" value="${balanceInstance?.id}" />
<g:link class="edit" action="edit" id="${balanceInstance?.id}"><g:message code="default.button.edit.label" default="Edit" /></g:link>
<g:actionSubmit class="delete" action="delete" value="${message(code: 'default.button.delete.label', default: 'Delete')}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');" />
</fieldset>
</g:form>
</div>
</body>
</html>
|
const { errorResponse } = require('../middleware/ErrorHandler');
const User = require('../models/user.schema');
module.exports.RequestConnection = async (req, res) => {
try {
let otherUserId = req.body.otherUserId;
// Find the user sending the request
let loggedInUserId = req.userData.id;
let loggedInUser = await User.findById(loggedInUserId);
// Find the user to whom the connection request is being sent
let requestedUser = await User.findById(otherUserId);
// Check if both users exist
if (!loggedInUser || !requestedUser) {
return res.status(404).json({ message: 'User not found' });
}
// Add the connection request to the requested user's pending list
requestedUser.pending.push({ email: loggedInUser.email, name: loggedInUser.name });
await requestedUser.save();
return res.status(200).json({ message: 'Connection request sent successfully' });
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.RespondToRequest = async (req, res) => {
try {
// const { email, name, accept } = req.body; // Assuming email, name, and accept (boolean) are provided in the request body
let otherUserId = req.body.otherUserId;
let accept = req.body.accept;
// Find the user responding to the request
// const respondingUser = await User.findOne({ email });
let loggedInUserId = req.userData.id;
let loggedInUser = await User.findById(loggedInUserId);
// Find the user who sent the connection request
let otherUser = await User.findById(otherUserId);
// Check if both users exist
if (!loggedInUser || !otherUser) {
return res.status(404).json({ message: 'User not found' });
}
// Remove the connection request from the responding user's pending list
loggedInUser.pending = loggedInUser.pending.filter((request) => request.email !== otherUser.email);
if (accept) {
// Add the requesting user to the responding user's connections list
loggedInUser.connections.push({ email: otherUser.email, name: otherUser.name });
// Add the responding user to the requesting user's connections list
otherUser.connections.push({ email: loggedInUser.email, name: loggedInUser.name });
}
await Promise.all([loggedInUser.save(), otherUser.save()]);
return res.status(200).json({ message: 'Connection request responded successfully' });
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.WithdrawConnection = async (req, res) => {
try {
let otherUserId = req.body.otherUserId;
// Find the user withdrawing the connection request
let loggedInUserId = req.userData.id;
let loggedInUser = await User.findById(loggedInUserId);
// Find the user to whom the connection request was sent
let requestedUser = await User.findById(otherUserId);
// Check if both users exist
if (!loggedInUser || !requestedUser) {
return res.status(404).json({ message: 'User not found' });
}
// Remove the connection request from the requested user's pending list
requestedUser.pending = requestedUser.pending.filter((request) => request.email !== loggedInUser.email);
await requestedUser.save();
return res.status(200).json({ message: 'Connection request withdrawn successfully' });
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.GetAllConnections = async (req, res) => {
try {
let otherUserId = req.body.otherUserId;
// Find the user to whom the connection request was sent
let otherUser = await User.findById(otherUserId);
return res.status(200).json({
no_of_connections: otherUser.connections.length,
connections_data: otherUser.connections,
});
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.GetPendingRequests = async (req, res) => {
try {
let userId = req.userData.id;
let user = await User.findById(userId);
return res.status(200).json({
no_of_pending_connections: user.pending.length,
pending_connections_data: user.pending,
});
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
// See how/when this endpoint need to be triggered ...
module.exports.GetEligibleRewards = async (req, res) => {
try {
let userId = req.userData.id;
let user = await User.findById(userId);
let connections = user.connections.length;
if(connections < 50) {
user.activityLevel = 0;
user.save();
} else if(connections > 50 && connections < 100) {
user.activityLevel = 5;
user.save();
} else if(connections > 100 && connections < 200) {
user.activityLevel = 10;
user.save();
} else if (connections > 200 && connections < 300) {
user.activityLevel = 20;
user.save();
} else if (connections > 300 && connections < 500) {
user.activityLevel = 50;
user.save();
} else if (connections > 500 && connections < 1000) {
user.activityLevel = 80;
user.save();
} else if (connections > 1000) {
user.activityLevel = 100;
user.save();
}
const activityWeight = 0.3;
const transactionWeight = 0.7;
// Calculate the reward based on activity level
const activityReward = user.activityLevel * activityWeight;
// Calculate the reward based on transaction history
const transactionReward = user.totalTransactions * transactionWeight;
const totalReward = activityReward + transactionReward;
return res.status(200).json({
activityReward : activityReward,
transactionReward: transactionReward,
totalReward: totalReward,
});
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.SetLendingStatus = async (req, res) => {
try {
let userId = req.userData.id;
let lend = req.body.canLend;
let Amount = req.body.Amount;
let user = await User.findById(userId);
let message = null;
if(lend == true && Amount > 0) {
message = "Able to Lend!";
user.canLend = lend;
user.lendAmount = Amount;
user.save();
} else if (lend == true && Amount <= 0) {
message = "Change lending status as lending amount is 0!";
} else if (lend == false && Amount == 0) {
message = "Not Able to Lend!";
user.canLend = lend;
user.lendAmount = Amount;
user.save();
} else if (lend == false && Amount > 0) {
message = "Change lending status as lending amount is greater than 0!";
}
return res.status(200).json({
message : message,
canLend: user.canLend,
lendAmount: user.lendAmount,
});
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.SearchConnections = async (req, res) => {
try {
let userId = req.userData.id;
let searchTerm = req.body.searchTerm;
let user = await User.findById(userId);
// Search connections by the searchTerm
const connections = user.connections.filter(connection =>
connection.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return res.status(200).json({
message: "Fetched results for the search",
searchResult : connections
});
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal server error' });
}
};
module.exports.LoadFunds = async (req, res) => {
// open paypal send to page send to merchant businees email id
// when this transaction is success receive the amount transacted and status
// if status is ok then update the wallet of that amount tansacted
};
|
package cn.edu.gdmec.w07150837.myguard.m4appmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import cn.edu.gdmec.w07150837.myguard.R;
import cn.edu.gdmec.w07150837.myguard.m4appmanager.adapter.AppManagerAdapter;
import cn.edu.gdmec.w07150837.myguard.m4appmanager.entity.AppInfo;
import cn.edu.gdmec.w07150837.myguard.m4appmanager.utils.AppInfoParser;
/**
* Created by weiruibo on 12/20/16.
*/
public class AppManagerActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mPhoneMemoryTV;
private TextView mSDMemoryTV;
private ListView mListView;
private List<AppInfo> appInfos;
private List<AppInfo> userAppInfos = new ArrayList<AppInfo>();
private List<AppInfo> systemAppInfos = new ArrayList<AppInfo>();
private AppManagerAdapter adapter;
private UninstallRececiver receiver;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 10:
if (adapter == null) {
adapter = new AppManagerAdapter(userAppInfos, systemAppInfos, AppManagerActivity.this);
}
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
case 15:
adapter.notifyDataSetChanged();
break;
}
}
;
};
private TextView mAppNumTV;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_app_manager);
receiver = new UninstallRececiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
registerReceiver(receiver, intentFilter);
initView();
}
private void initView() {
findViewById(R.id.r1_titlebar).setBackgroundColor(getResources().getColor(R.color.bright_yellow));
ImageView mLeftImgv = (ImageView) findViewById(R.id.imgv_leftbtn);
((TextView) findViewById(R.id.tv_title)).setText("软件管家");
mLeftImgv.setOnClickListener(this);
mLeftImgv.setImageResource(R.drawable.back);
mPhoneMemoryTV = (TextView) findViewById(R.id.tv_phonememory_appmanager);
mSDMemoryTV = (TextView) findViewById(R.id.tv_sdmemory_appmanager);
mAppNumTV = (TextView) findViewById(R.id.tv_appnumber);
mListView = (ListView) findViewById(R.id.lv_appmanager);
getMemoryFromPhone();
initData();
initListener();
}
private void initListener() {
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
if (adapter != null) {
new Thread() {
public void run() {
// adapter.getItem 位置为0和userAppInfos.size() + 1 时
// 返回的是null 故取不到AppInfo对象点击时就会报错
if (position != 0 && position != userAppInfos.size() + 1) {
AppInfo mappInfo = (AppInfo) adapter.getItem(position);
boolean flag = mappInfo.isSelected;
for (AppInfo appInfo : userAppInfos) {
appInfo.isSelected = false;
}
for (AppInfo appInfo : systemAppInfos) {
appInfo.isSelected = false;
}
if (mappInfo != null) {
if (flag) {
mappInfo.isSelected = false;
} else {
mappInfo.isSelected = true;
}
mHandler.sendEmptyMessage(15);
}
}
}
;
}.start();
}
}
});
mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scroolState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem >= userAppInfos.size() + 1) {
mAppNumTV.setText("系统程序:" + systemAppInfos.size() + "个");
} else {
mAppNumTV.setText("用户程序:" + userAppInfos.size() + "个");
}
}
});
}
private void initData() {
appInfos = new ArrayList<AppInfo>();
new Thread() {
public void run() {
appInfos.clear();
userAppInfos.clear();
systemAppInfos.clear();
appInfos.addAll(AppInfoParser.getAppInfo(AppManagerActivity.this));
for (AppInfo appInfo : appInfos) {
if (appInfo.isUserApp) {
userAppInfos.add(appInfo);
} else {
systemAppInfos.add(appInfo);
}
}
mHandler.sendEmptyMessage(10);
}
;
}.start();
}
private void getMemoryFromPhone() {
long avail_sd = Environment.getExternalStorageDirectory().getFreeSpace();
long avail_rom = Environment.getDataDirectory().getFreeSpace();
String str_avail_sd = Formatter.formatFileSize(this, avail_sd);
String str_avail_rom = Formatter.formatFileSize(this, avail_rom);
mPhoneMemoryTV.setText("剩余手机内存:" + str_avail_rom);
mSDMemoryTV.setText("剩余SD卡内存:" + str_avail_sd);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgv_leftbtn:
finish();
break;
}
}
class UninstallRececiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
initData();
}
}
protected void onDestory() {
unregisterReceiver(receiver);
receiver = null;
super.onDestroy();
}
}
|
import classNames from 'lib/classNames'
export type StackSpacing =
| 'none'
| 'px'
| 'mini'
| 'small'
| 'default'
| 'large'
| 'huge'
| 'enormous'
| 'gigantic'
| 'colossal'
type StackAlignment = 'start' | 'center' | 'end' | 'stretch' | 'between'
export type IStack = {
direction?: 'vertical' | 'horizontal'
justify?: StackAlignment
spacing?: StackSpacing
align?: StackAlignment
wrap?: boolean
} & React.HTMLAttributes<HTMLDivElement>
const Stack = ({
direction = 'horizontal',
spacing = 'default',
justify = 'stretch',
align = 'stretch',
children,
wrap,
...rest
}: IStack) => {
const spacingToGap: Record<StackSpacing, string> = {
px: 'px',
none: '0',
mini: '1',
small: '2',
default: '3',
large: '4',
huge: '5',
enormous: '6',
gigantic: '7',
colossal: '8',
}
const spacingAmount = spacingToGap[spacing]
return (
<div
{...rest}
className={classNames(
`flex items-${align} justify-${justify} gap-${spacingAmount}`,
direction === 'horizontal' ? 'flex-row' : 'flex-col',
wrap && 'flex-wrap',
rest.className
)}
>
{children}
</div>
)
}
export default Stack
|
use bevy::{
input::{mouse::MouseWheel, touch::TouchPhase},
prelude::*,
render::camera::RenderTarget,
window::{PrimaryWindow, WindowRef},
};
use super::{TrackballCamera, TrackballController};
/// Trackball viewport currently focused and hence capturing input events.
///
/// * Enables multiple viewports/windows with individual controllers/cameras.
/// * Enables UI systems to steal the viewport in order to capture input events.
#[derive(Resource, Clone, Debug, PartialEq, Eq, Default)]
pub struct TrackballViewport {
entity: Option<Entity>,
stolen: usize,
}
impl TrackballViewport {
/// Condition whether the viewport has been stolen, evaluated by [`IntoSystemConfigs::run_if`].
///
/// Interferes with automatic viewport stealing if the `bevy_egui` feature is enabled. As
/// automatic viewport stealing gives the viewport back with `set_stolen(None)` instead of
/// `set_stolen(Some(0))`, you can override it in the same frame for your own input capturing.
#[allow(clippy::needless_pass_by_value)]
#[must_use]
pub fn stolen(viewport: Res<Self>) -> bool {
viewport.stolen != 0
}
/// Whether viewport has just been given back.
///
/// Interferes with automatic viewport stealing if the `bevy_egui` feature is enabled. As
/// automatic viewport stealing gives the viewport back with `set_stolen(None)` instead of
/// `set_stolen(Some(0))`, you can override it in the same frame for your own input capturing.
#[must_use]
pub const fn was_stolen(&self) -> bool {
self.entity.is_none()
}
/// Steals the viewport or gives it back.
///
/// Interferes with automatic viewport stealing if the `bevy_egui` feature is enabled. As
/// automatic viewport stealing gives the viewport back with `set_stolen(None)` instead of
/// `set_stolen(Some(0))`, you can override it in the same frame for your own input capturing.
///
/// # Examples
///
/// Steals the viewport for `Some(frames)` and lets it count `frames` down with `None`:
///
/// ```ignore
/// fn system(/* ... */) {
/// viewport.set_stolen(just_stolen.then_some(3));
/// }
///
/// // frame 0: just_stolen = true -> set_stolen(Some(3)) -> frames = 3 -> stolen = true
/// // frame 1: just_stolen = false -> set_stolen(None) -> frames = 2 -> stolen = true
/// // frame 2: just_stolen = false -> set_stolen(None) -> frames = 1 -> stolen = true
/// // frame 3: just_stolen = false -> set_stolen(None) -> frames = 0 -> stolen = false
/// ```
///
/// Steals the viewport with `Some(1)` and gives it back with `Some(0)`:
///
/// ```ignore
/// fn system(/* ... */) {
/// if just_stolen {
/// viewport.set_stolen(Some(1));
/// }
/// if just_give_back {
/// viewport.set_stolen(Some(0));
/// }
/// }
///
/// // frame 0: just_stolen = true -> set_stolen(Some(1)) -> frames = 1 -> stolen = true
/// // frame 1: just_stolen = false -> -> frames = 1 -> stolen = true
/// // frame 25: just_stolen = false -> -> frames = 1 -> stolen = true
/// // frame 50: just_give_back = true -> set_stolen(Some(0)) -> frames = 0 -> stolen = false
/// ```
#[allow(clippy::needless_pass_by_value)]
pub fn set_stolen(&mut self, stolen: Option<usize>) {
if let Some(frames) = stolen {
self.entity = None;
self.stolen = frames;
} else if self.stolen != 0 {
self.stolen -= 1;
}
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
pub(super) fn select<'a>(
viewport: &mut ResMut<Self>,
key_input: &Res<ButtonInput<KeyCode>>,
mouse_input: &Res<ButtonInput<MouseButton>>,
touch_events: &mut EventReader<TouchInput>,
wheel_events: &EventReader<MouseWheel>,
primary_windows: &'a mut Query<&mut Window, With<PrimaryWindow>>,
secondary_windows: &'a mut Query<&mut Window, Without<PrimaryWindow>>,
cameras: &'a mut Query<(Entity, &Camera, &TrackballCamera, &mut TrackballController)>,
) -> Option<(
bool,
Mut<'a, Window>,
Entity,
&'a Camera,
&'a TrackballCamera,
Mut<'a, TrackballController>,
)> {
let touch = touch_events
.read()
.filter_map(|touch| (touch.phase == TouchPhase::Started).then_some(touch.position))
.last();
let input = !wheel_events.is_empty()
|| key_input.get_just_pressed().len() != 0
|| mouse_input.get_just_pressed().len() != 0;
let mut new_viewport = viewport.clone();
let mut max_order = 0;
for (entity, camera, _trackball, _controller) in cameras.iter() {
let RenderTarget::Window(window_ref) = camera.target else {
continue;
};
let window = match window_ref {
WindowRef::Primary => primary_windows.get_single().ok(),
WindowRef::Entity(entity) => secondary_windows.get(entity).ok(),
};
let Some(window) = window else {
continue;
};
let Some(pos) = touch
.filter(|_pos| window.focused)
.or_else(|| window.cursor_position().filter(|_pos| input))
else {
continue;
};
let Some(Rect { min, max }) = camera.logical_viewport_rect() else {
continue;
};
let contained = (min.x..max.x).contains(&pos.x) && (min.y..max.y).contains(&pos.y);
if contained && camera.order >= max_order {
new_viewport.entity = Some(entity);
max_order = camera.order;
}
}
let is_changed = viewport.entity != new_viewport.entity;
if is_changed {
viewport.entity = new_viewport.entity;
}
let camera = viewport
.entity
.and_then(|entity| cameras.get_mut(entity).ok());
let Some((entity, camera, trackball, controller)) = camera else {
viewport.entity = None;
return None;
};
let RenderTarget::Window(window_ref) = camera.target else {
return None;
};
let window = match window_ref {
WindowRef::Primary => primary_windows.get_single_mut().ok(),
WindowRef::Entity(entity) => secondary_windows.get_mut(entity).ok(),
}?;
Some((is_changed, window, entity, camera, trackball, controller))
}
}
|
import { MdFavorite, MdFavoriteBorder } from "react-icons/md";
import { useGlobalContext } from "../context";
const Meal = ({ meal }) => {
const { selectMeal, addToFavorites, removeFromFavorites, favorites } =
useGlobalContext();
const { idMeal, strMeal: mealTitle, strMealThumb: mealPhoto } = meal;
const toggleFavorite = (isFavorite, idMeal) => {
isFavorite ? removeFromFavorites(idMeal) : addToFavorites(idMeal);
};
const isFavorite = favorites.find((meal) => meal.idMeal === idMeal);
return (
<article className="meal" key={idMeal}>
<img
className="meal__image"
src={mealPhoto}
alt="meal-photo"
onClick={() => selectMeal(idMeal, isFavorite)}
/>
<footer className="meal__info">
<h5 className="meal__title">{mealTitle}</h5>
<button
className="meal__like-btn"
onClick={() => toggleFavorite(isFavorite, idMeal)}
>
{isFavorite ? <MdFavorite /> : <MdFavoriteBorder />}
</button>
</footer>
</article>
);
};
export default Meal;
|
import * as React from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import CssBaseline from "@mui/material/CssBaseline";
import Grid from "@mui/material/Grid";
import Stack from "@mui/material/Stack";
import Step from "@mui/material/Step";
import StepLabel from "@mui/material/StepLabel";
import Stepper from "@mui/material/Stepper";
import Typography from "@mui/material/Typography";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import ChevronRightRoundedIcon from "@mui/icons-material/ChevronRightRounded";
import AddressForm from "./AddressForm";
import getCheckoutTheme from "./getCheckoutTheme";
import Info from "./Info";
import InfoMobile from "./InfoMobile";
import { LogoBlack } from "../SvgImages";
import StripeCheckout from "./StripeCheckout";
const steps = ["Shipping address", "Payment details"];
export default function Checkout() {
const checkoutTheme = createTheme(getCheckoutTheme("light"));
const [activeStep, setActiveStep] = React.useState(0);
const [clientData, setClientData] = React.useState();
const handleNext = () => {
setActiveStep(activeStep + 1);
};
const handleBack = () => {
setActiveStep(activeStep - 1);
};
function getStepContent(step) {
switch (step) {
case 0:
return (
<AddressForm handleNext={handleNext} setClientData={setClientData} />
);
case 1:
return (
<StripeCheckout
clientData={clientData}
handleNext={handleNext}
handleBack={handleBack}
/>
);
default:
throw new Error("Unknown step");
}
}
return (
<ThemeProvider theme={checkoutTheme}>
<CssBaseline />
<Grid container sx={{ height: { xs: "100%", sm: "100dvh" } }}>
<Grid
item
xs={12}
sm={5}
lg={4}
sx={{
display: { xs: "none", md: "flex" },
flexDirection: "column",
backgroundColor: "background.paper",
borderRight: { sm: "none", md: "1px solid" },
borderColor: { sm: "none", md: "divider" },
alignItems: "start",
pt: 4,
px: 10,
gap: 4,
}}
>
<Box
sx={{
display: "flex",
alignItems: "end",
height: 150,
}}
>
<Button
startIcon={<ArrowBackRoundedIcon />}
component="a"
href="/"
sx={{ ml: "-8px" }}
>
Back to <LogoBlack />
</Button>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
flexGrow: 1,
width: "100%",
maxWidth: 500,
}}
>
<Info totalPrice="$49.99" />
</Box>
</Grid>
<Grid
item
sm={12}
md={7}
lg={8}
sx={{
display: "flex",
flexDirection: "column",
maxWidth: "100%",
width: "100%",
backgroundColor: { xs: "transparent", sm: "background.default" },
alignItems: "start",
pt: { xs: 2, sm: 4 },
px: { xs: 2, sm: 10 },
gap: { xs: 4, md: 8 },
}}
>
<Box
sx={{
display: "flex",
justifyContent: { sm: "space-between", md: "flex-end" },
alignItems: "center",
width: "100%",
maxWidth: { sm: "100%", md: 600 },
}}
>
<Box
sx={{
display: { xs: "flex", md: "none" },
flexDirection: "row",
width: "100%",
justifyContent: "space-between",
}}
>
<Button
startIcon={<ArrowBackRoundedIcon />}
component="a"
href="/"
sx={{ alignSelf: "start" }}
>
Back to
<LogoBlack />
</Button>
</Box>
<Box
sx={{
display: { xs: "none", md: "flex" },
flexDirection: "column",
justifyContent: "space-between",
alignItems: "flex-end",
flexGrow: 1,
}}
>
<Stepper
id="desktop-stepper"
activeStep={activeStep}
sx={{
width: "100%",
}}
>
{steps.map((label) => (
<Step
sx={{
":first-of-type": { pl: 0 },
":last-child": { pr: 0 },
}}
key={label}
>
<StepLabel>{label}</StepLabel>
</Step>
))}
</Stepper>
</Box>
</Box>
<Card
sx={{
display: { xs: "flex", md: "none" },
width: "100%",
}}
>
<CardContent
sx={{
display: "flex",
width: "100%",
alignItems: "center",
justifyContent: "space-between",
":last-child": { pb: 2 },
}}
>
<div>
<Typography variant="subtitle2" gutterBottom>
Selected products
</Typography>
<Typography variant="body1">$49.99</Typography>
</div>
<InfoMobile totalPrice="$49.99" />
</CardContent>
</Card>
<Box
sx={{
display: "flex",
flexDirection: "column",
flexGrow: 1,
width: "100%",
maxWidth: { sm: "100%", md: 600 },
maxHeight: "720px",
gap: { xs: 5, md: "none" },
}}
>
<Stepper
id="mobile-stepper"
activeStep={activeStep}
alternativeLabel
sx={{ display: { sm: "flex", md: "none" } }}
>
{steps.map((label) => (
<Step
sx={{
":first-of-type": { pl: 0 },
":last-child": { pr: 0 },
"& .MuiStepConnector-root": { top: { xs: 6, sm: 12 } },
}}
key={label}
>
<StepLabel
sx={{
".MuiStepLabel-labelContainer": { maxWidth: "70px" },
}}
>
{label}
</StepLabel>
</Step>
))}
</Stepper>
{activeStep === steps.length ? (
<Stack spacing={2} useFlexGap>
<Typography variant="h1">📦</Typography>
<Typography variant="h5">Thank you for your order!</Typography>
<Typography variant="body1" color="text.secondary">
Your order number is
<strong> #140396</strong>. We have emailed your order
confirmation and will update you once its shipped.
</Typography>
<Button
variant="contained"
sx={{
alignSelf: "start",
width: { xs: "100%", sm: "auto" },
}}
>
Go to my orders
</Button>
</Stack>
) : (
<React.Fragment>
{getStepContent(activeStep)}
<Box
sx={{
display: "flex",
flexDirection: { xs: "column-reverse", sm: "row" },
justifyContent:
activeStep !== 0 ? "space-between" : "flex-end",
alignItems: "end",
flexGrow: 1,
gap: 1,
pb: { xs: 12, sm: 0 },
mt: { xs: 2, sm: 0 },
mb: "60px",
}}
></Box>
</React.Fragment>
)}
</Box>
</Grid>
</Grid>
</ThemeProvider>
);
}
|
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<h1>LBX Task Documentation</h1>
<h2>Live Demo</h2>
<strong>Please watch this video 👇</strong>
[](https://youtu.be/8rP9GRuBH-w)
<li> Please run "Truncate DB API" Firstly for a clean demo database
<ul>To keep it simple for you the project is :
<li> Deployed at Heroku Free Serverless Host with Jaws Free 10 MB DB
<br>
<a target="_blank" href="http://lbx-task-ac05b2f76b97.herokuapp.com/api/documentation#/Demo/truncateDB">Heroku Swagger Open API</a>
<li> Dockerized using laravel sail to run it locally
<br>
<a target="_blank" href="http://localhost:8000/api/documentation#/Demo/truncateDB">Local Swagger Open API</a>
</ul>
<h2>Project Infra Structure</h2>
<ul>
<li> The Project is a Decoupled Modular Monolithic App :
HMVC Modules (you can turn on/off each module and republish/reuse it at another project)
<p>
<a target="_blank" href="https://drive.google.com/uc?export=view&id=1DT3YIcfRSaU_SeiSzPht_vljOWu745Sr">
<img src="https://drive.google.com/uc?export=view&id=1DT3YIcfRSaU_SeiSzPht_vljOWu745Sr" width="200" height="200">
</a>
<a target="_blank" href="https://drive.google.com/uc?export=view&id=18jSzl7SrJKevpDNko9kgWgvZLWJwXK_Y">
<img src="https://drive.google.com/uc?export=view&id=18jSzl7SrJKevpDNko9kgWgvZLWJwXK_Y" width="200" height="200">
</a>
</p>
<li> Module Structure (Repository Design Pattern)
<p>
<a target="_blank" href="https://drive.google.com/uc?export=view&id=1_CTRCCiZ0X4nG06_xTv48y6MH5vBb1gx">
<img src="https://drive.google.com/uc?export=view&id=1_CTRCCiZ0X4nG06_xTv48y6MH5vBb1gx" width="400" height="200">
</a>
</p>
<li> Separated/Attached Tests
<p>
<a target="_blank" href="https://drive.google.com/uc?export=view&id=1JzE_2ZtJXvIZjWXmb_tZUAmE3gsHgdD4">
<img src="https://drive.google.com/uc?export=view&id=1JzE_2ZtJXvIZjWXmb_tZUAmE3gsHgdD4" width="200" height="200">
</a>
</p>
</ul>
<h2>Import Solution Implementation</h2>
<pre>
Preparation :
- validate excel-sheet file memType and Extension
- upload it at S3 Bucket with status = "Processing"
----------------
Execution : 2 Background Job Queue Buses (groups)
are chained in chunks (Read 1000 Record/ChunkedJob) :
- Validator : validate records
- Importer : Import records if the all the excel-sheet is Valid with ability
to rollback in case of failure
- Updates Url : show the updated status of file validation and importation
so front end can utilize it with ajax to update the UI continuously
----------------
* Recommendation :
we can utilize after import and validation event-listener not only to
update file status but also for send the user updates via email
</pre>
<h3>How To Run The Project Locally</h3>
<pre>
Requirements (all can be installed automatically using docker desktop):
---------------
- PHP 8.2
- Run Docker Desktop
- MYSQL
- SQL lite PHP Extension
<hr>
Run the following at the project root dir Terminal
---------------
<ul>
<li>Download Vendor folder
composer install
<li>Make Sail alias
alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'
<li>Generate .env file from .env.decrypted:
php artisan env:decrypt --key="base64:IMQS06IFVHHEqYuLNYQRQ1XYEyEXUr57kNXqkpBIPlo="
<li>Laravel Sail install
php artisan sail:install
<li>Make an alias for ./vendor/bin/sail:
alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'
<li>Make an alias for ./vendor/bin/sail:
alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'
<li>Run Your local server up:
sail up -d
<li>Run Your local server down:
sail down
<li>To Run Unit/Feature Tests but configure your test with xdebug
php artisan test --testsuite=Employee
</ul>
if you have an issue you can see <a href="https://laravel.com/docs/10.x/sail">Laravel Sail</a>
</pre>
|
package com.momolela.readpdf;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* 版权:版权所有 bsoft 保留所有权力。
*
* @author <a href="mailto:[email protected]">sunzj</a>
* @description
* @date 2023/10/7 15:41
*/
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
App app = new App();
try {
// 取得E盘下的SpringGuide.pdf的内容
System.out.println("开始提取");
File file = new File("a.pdf");
System.out.println("文件绝对路径为:" + file.getAbsolutePath());
app.readPdf(file);
System.out.println("提取结束");
} catch (Exception e) {
e.printStackTrace();
}
}
public void readPdf(File pdfFile) throws Exception {
// 是否排序
boolean sort = false;
// 输入文本文件名称
String textFileName = null;
// 编码方式
String encoding = "UTF-8";
// 开始提取页数
int startPage = 1;
// 结束提取页数
int endPage = 3;
// 文件输入流,生成文本文件
Writer output = null;
// 内存中存储的 PDF Document
PDDocument document = null;
File outputFile = null;
try {
// 从本地装载文件
// 注意参数已不是以前版本中的 URL.而是 File。
System.out.println("开始装载文件" + pdfFile.getName());
document = PDDocument.load(pdfFile);
if (pdfFile.getName().length() > 4) {
textFileName = pdfFile.getName().substring(0, pdfFile.getName().length() - 4) + ".txt";
outputFile = new File(pdfFile.getParent(), textFileName);
System.out.println("新文件绝对路径为:" + outputFile.getAbsolutePath());
}
System.out.println("装载文件结束");
System.out.println("开始写到txt文件中");
// 文件输入流,写入文件倒textFile
output = new OutputStreamWriter(new FileOutputStream(outputFile), encoding);
System.out.println("写入txt文件结束");
// PDFTextStripper来提取文本
PDFTextStripper stripper = null;
stripper = new PDFTextStripper();
// 设置是否排序
stripper.setSortByPosition(sort);
// 设置起始页
stripper.setStartPage(startPage);
// 设置结束页
stripper.setEndPage(endPage);
// 调用PDFTextStripper的writeText提取并输出文本
System.out.println("开始调用writeText方法");
stripper.writeText(document, output);
System.out.println("调用writeText方法结束");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
// 关闭输出流
output.close();
}
if (document != null) {
// 关闭PDF Document
document.close();
}
}
}
}
|
import { useEffect, useState } from "react";
import "./App.css";
import dice from "./assets/icon-dice.svg";
type AdviceType = {
id: number;
advice: string;
};
function getAdvice() {
return fetch("https://api.adviceslip.com/advice")
.then((response) => response.json())
.then((data) => {
return {
id: data.slip.id,
advice: data.slip.advice,
};
});
}
function App() {
const [advice, setAdvice] = useState<AdviceType>();
useEffect(() => {
getAdvice().then((advice) => {
setAdvice(advice);
});
}, []);
const rerollAdvice = () => {
getAdvice().then((advice) => {
setAdvice(advice);
});
};
return (
<div className="container">
{!advice ? null : (
<div className="box">
<h4>ADVICE #{advice.id}</h4>
<h1>"{advice.advice}"</h1>
<div className="dice" onClick={rerollAdvice}>
<img src={dice} alt="dice" />
</div>
</div>
)}
</div>
);
}
export default App;
|
import { RequestHandler } from "express";
import { z } from "zod";
import { handleError } from "../errors/error-hendler";
import { HttpError } from "../errors/http-error";
const PlayerRoles: PlayerRolesArrayType = [
"Goalkeepers",
"Defenders",
"Midfielders",
"Forwards",
];
export const playerFilter = [...PlayerRoles, "All"] as const;
export class PlayerController implements PlayerControllerInterface {
constructor(private playerService: PlayerServiceInterface) {}
getPaginatedPlayers: RequestHandler = async (req, res, next) => {
try {
const inputs = z
.object({
num: z.string().regex(/^\d+$/).default("20").transform(Number),
page: z.string().regex(/^\d+$/).default("1").transform(Number),
search: z.string().default(""),
role: z.enum(playerFilter).default("All"),
order: z.string().default("DESC"),
sortBy: z.string().default("price"),
})
.parse(req.query);
let data = await this.playerService.getPaginatedPlayers(inputs);
return res.status(200).json(data);
} catch (err) {
handleError(err);
}
};
getPlayer: RequestHandler = async (req, res, next) => {
try {
const { playerId } = z
.object({ playerId: z.string().regex(/^\d+$/).transform(Number) })
.parse(req.params);
let player = await this.playerService.getPlayerById(playerId);
if (player instanceof HttpError) player.throw();
else res.status(200).json({ player });
} catch (err) {
handleError(err);
}
};
}
|
# Public Key Cryptography (Assignment 5)
## Description
This is a project that uses different c programs to encrypt and decrypt a file using a public and private key's. The keygen program gernerates a public and private key and stores them into two seperate files. The encrypt executable takes a public key and encrypts a file that is passed and saves it to another file. Finally the decrypt executable takes the private key from a file and decrypts an encrypted file and then writes the result to another file.
This is a response to [assignment5](https://git.ucsc.edu/cse13s/winter2023-section01/resources/-/blob/main/asgn5/asgn5.pdf) in [Cse13s course](https://git.ucsc.edu/cse13s/winter2023-section01/resources)
## Installation
First you need to compile all appropirate c files to create sorting: run make as follows
```
make clean && make
```
## Usage
To run this program run keygen as follows
```
./keygen
```
You can use additional options.
The opitions can be seen with -h command:
```
SYNOPSIS
Creates a public and private key
USAGE
./keygen [options]
OPTIONS
-b : specifies the minimum bits needed for the public modulus n
-i : specifies the number of Miller-Rabin iterations for testing primes (default: 50)
-n pbfile : specifies the public key file (default: ss.pub)
-d pvfile : specifies the private key file (default: ss.priv)
-s : specifies the random seed for the random state initialization
-v : enables verbose output
-h : display program help and usage
```
To run encrypt run as follows
```
./encrypt
```
You can use additional options.
The opitions can be seen with -h command:
```
SYNOPSIS
encrypts file
USAGE
./encrypt [options]
OPTIONS
-i input : specifices the input file to encrypt (default: stdin)
-o output : specifies the output file to encrypt (default: stdout)
-n : specifies the file containing the public key (default: ss.pub)
-v : enables verbose output
-h : display program help and usage.
```
To run decrypt run as follows
```
./decrypt
```
You can use additional options.
The opitions can be seen with -h command:
```
SYNOPSIS
Decrypts file
USAGE
./decrypt [options]
OPTIONS
-i input : specifices the input file to decrypt (default: stdin)
-o output : specifies the output file to decrypt (default: stdout)
-n : specifies the file containing the private key (default: ss.priv)
-v : enables verbose output
-h : display program help and usage.
```
## False Positive from scan-build
scan-build complains about memory leak in memory pointed by private_key_file_name, in_file_name, out_file_name, public_key_file_name
I believe these reports to be false positives because at the end of each program I free all pointers
```
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -c decrypt.c
decrypt.c:36:17: warning: Potential leak of memory pointed to by 'private_key_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "hvn:i:o:")) != -1) {
^~~~~~
decrypt.c:36:17: warning: Potential leak of memory pointed to by 'in_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "hvn:i:o:")) != -1) {
^~~~~~
decrypt.c:36:17: warning: Potential leak of memory pointed to by 'out_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "hvn:i:o:")) != -1) {
^~~~~~
3 warnings generated.
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -c randstate.c
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -c numtheory.c
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -c ss.c
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -o decrypt decrypt.o randstate.o numtheory.o ss.o -lgmp
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -c encrypt.c
encrypt.c:37:17: warning: Potential leak of memory pointed to by 'public_key_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "hvn:i:o:")) != -1) {
^~~~~~
encrypt.c:37:17: warning: Potential leak of memory pointed to by 'in_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "hvn:i:o:")) != -1) {
^~~~~~
encrypt.c:37:17: warning: Potential leak of memory pointed to by 'out_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "hvn:i:o:")) != -1) {
^~~~~~
3 warnings generated.
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -o encrypt encrypt.o randstate.o numtheory.o ss.o -lgmp
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -c keygen.c
keygen.c:43:17: warning: Potential leak of memory pointed to by 'private_key_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "b:i:n:d:s:vh")) != -1) {
^~~~~~
keygen.c:43:17: warning: Potential leak of memory pointed to by 'public_key_file_name' [unix.Malloc]
while ((c = getopt(argc, argv, "b:i:n:d:s:vh")) != -1) {
^~~~~~
2 warnings generated.
/usr/share/clang/scan-build-14/bin/../libexec/ccc-analyzer -Wall -Wpedantic -Werror -Wextra -g -o keygen keygen.o randstate.o numtheory.o ss.o -lgmp
scan-build: Analysis run complete.
scan-build: 5 bugs found.
```
## Support
Please contact [email protected] if you need help or provide feedback for this project
## Author
Michael V. Kamensky
|
import "@testing-library/jest-dom";
import { render, screen, cleanup } from "@testing-library/react";
import {
AccordionContainer,
Accordion,
AccordionHead,
AccordionBody,
} from "./index";
afterEach(cleanup);
describe("Accordion Component", () => {
it("renders Accordion component correctly", () => {
render(
<AccordionContainer>
<Accordion>
<AccordionHead
onAccordionToggle={jest.fn()}
children="Accordion Head"
/>
<AccordionBody isOpen={false} children="Accordion Body" />
</Accordion>
</AccordionContainer>
);
const accordionContainer = screen.getByTestId("accordion-container");
const accordion = screen.getByTestId("accordion");
expect(accordionContainer).toBeInTheDocument();
expect(accordion).toBeInTheDocument();
});
it("should toggle its visibility when isOpen changes", () => {
const { rerender } = render(
<AccordionBody isOpen={false}>Accordion Body Content</AccordionBody>
);
const accordionBody = screen.getByTestId("accordion-body");
// Initially hidden
expect(accordionBody).toHaveClass("max-h-[0px]");
// Update isOpen to true
rerender(
<AccordionBody isOpen={true}>Accordion Body Content</AccordionBody>
);
// Now visible
expect(accordionBody).toHaveClass("max-h-screen");
// Update isOpen to false
rerender(
<AccordionBody isOpen={false}>Accordion Body Content</AccordionBody>
);
// Back to hidden
expect(accordionBody).toHaveClass("max-h-[0px]");
});
it("handles starred AccordionHead correctly", () => {
render(
<AccordionContainer>
<Accordion>
<AccordionHead
onAccordionToggle={jest.fn()}
starred={true}
onStar={jest.fn()}
children="Accordion Head"
/>
<AccordionBody isOpen={false} children="Accordion Body" />
</Accordion>
</AccordionContainer>
);
const starIcon = screen.getByTestId("star-icon");
expect(starIcon).toHaveClass("custom-fill-color-gray-400");
});
});
|
class UsersController < ApplicationController
before_action :authenticate_user!
def show
@user = User.find(params[:id])
@books = @user.books.page(params[:page])
@book = Book.new
@today_book = @books.created_today
@yesterday_book = @books.created_yesterday
@two_days_ago_book = @books.created_two_days_ago
@three_days_ago_book = @books.created_three_days_ago
@four_days_ago_book = @books.created_four_days_ago
@five_days_ago_book = @books.created_five_days_ago
@six_days_ago_book = @books.created_six_days_ago
@seven_days_ago_book = @books.created_seven_days_ago
@this_week_book = @books.created_this_week
@last_week_book = @books.created_last_week
end
def index
@book = Book.new
@user = current_user
@users = User.page(params[:page])
end
def edit
@user = User.find(params[:id])
if @user == current_user
render "edit"
else
redirect_to books_path
end
end
def update
@user = User.find(params[:id])
@books = Book.all
if @user.update(user_params)
redirect_to user_path(@user), notice: "You have updated user successfully."
else
render "edit"
end
end
private
def user_params
params.require(:user).permit(:name, :introduction, :profile_image)
end
def ensure_correct_user
@user = User.find(params[:id])
unless @user == current_user
redirect_to user_path(current_user)
end
end
end
|
import { createLogger, format, transports } from 'winston';
const customLevelsOptions = {
levels: {
fatal: 0,
error: 1,
warning: 2,
debug: 3,
info: 4,
},
colors: {
fatal: "red",
error: "orange",
warning: "yellow",
info: "blue",
debug: "white"
}
}
const { combine, timestamp, printf } = format;
const myFormat = printf(({ level, message, timestamp }) => {
return `[${timestamp}] ${level} : ${message}`;
});
//esta confi es solo para nivel console info y archivo warning
// export const logger = createLogger({
// levels: customLevelsOptions.levels,
// format: combine(
// timestamp(),
// myFormat
// ),
// transports: [
// new transports.Console({
// level: "info",
// format: combine(
// format.colorize({ colors: customLevelsOptions.colors }),
// format.simple()
// )
// }),
// new transports.File({
// filename: "./errors.log",
// level: 'warning',
// format: format.simple()
// })
// ]
// });
export const logger = createLogger({
levels: customLevelsOptions.levels,
format: combine(
timestamp(),
myFormat
),
transports: [
new transports.Console({
level: "debug", // Mostrar todos los niveles en la consola
format: combine(
format.colorize({ colors: customLevelsOptions.colors }),
format.simple()
)
}),
new transports.File({
filename: "./errors.log",
level: 'debug', // Registrar todos los niveles en el archivo
format: format.simple()
})
]
});
export const addLogger = (req, res, next) => {
req.logger = logger;
req.logger.info(`${req.method} en ${req.url} - ${new Date().toLocaleDateString()}`);
next();
}
|
/**
* test.c: Verify the migration from version 1 to version 2 wrapped-passphrase
* files
* Author: Tyler Hicks <[email protected]>
*
* Copyright (C) 2015 Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "../../src/include/tse.h"
#define TSE_MAX_KEY_HEX_BYTES (TSE_MAX_KEY_BYTES * 2)
#define NEW_WRAPPING_PASSPHRASE "The *new* Tse wrapping passphrase."
static void usage(const char *name)
{
fprintf(stderr,
"%s FILENAME EXPECTED_PASS WRAPPING_PASS WRAPPING_SALT_HEX\n",
name);
}
/**
* Returns 0 if the unwrap operation resulted in the expected decrypted
* passphrase
*/
static int verify_unwrap(char *expected_decrypted_passphrase, char *filename,
char *wrapping_passphrase, char *wrapping_salt)
{
char decrypted_passphrase[TSE_MAX_PASSPHRASE_BYTES + 1];
int rc;
memset(decrypted_passphrase, 0, sizeof(decrypted_passphrase));
rc = tse_unwrap_passphrase(decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
if (rc)
return 1;
if (strcmp(decrypted_passphrase, expected_decrypted_passphrase))
return 1;
return 0;
}
/**
* Returns 0 if the *invalid* unwrap operations always fail
*/
static int verify_bad_unwrap(char *expected_decrypted_passphrase, char *filename,
char *wrapping_passphrase, char *wrapping_salt)
{
char *last;
int rc;
/* Increment first char in the wrapping_passphrase and verify that the
* unwrapping operation fails */
wrapping_passphrase[0]++;
rc = verify_unwrap(expected_decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
wrapping_passphrase[0]--;
if (!rc)
return 1;
/* Increment last char in the wrapping_passphrase and verify that the
* unwrapping operation fails */
last = wrapping_passphrase + (strlen(wrapping_passphrase) - 1);
(*last)++;
rc = verify_unwrap(expected_decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
(*last)--;
if (!rc)
return 1;
/* Perform a one's complement on the first char in the salt and verify
* that the unwrapping operation fails */
wrapping_salt[0] = ~wrapping_salt[0];
rc = verify_unwrap(expected_decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
wrapping_salt[0] = ~wrapping_salt[0];
if (!rc)
return 1;
/* Perform a one's complement on the last char in the salt and verify
* that the unwrapping operation fails */
last = wrapping_salt + (TSE_SALT_SIZE - 1);
*last = ~(*last);
rc = verify_unwrap(expected_decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
*last = ~(*last);
if (!rc)
return 1;
return 0;
}
static int do_rewrap(char *filename, char *old_wrapping_passphrase,
char *old_wrapping_salt, char *new_wrapping_passphrase)
{
char decrypted_passphrase[TSE_MAX_PASSPHRASE_BYTES + 1];
uint8_t version = 0;
int rc;
memset(decrypted_passphrase, 0, sizeof(decrypted_passphrase));
rc = tse_unwrap_passphrase(decrypted_passphrase, filename,
old_wrapping_passphrase,
old_wrapping_salt);
if (rc)
return 1;
rc = tse_wrap_passphrase(filename, new_wrapping_passphrase, NULL,
decrypted_passphrase);
if (rc)
return 1;
rc = __tse_detect_wrapped_passphrase_file_version(filename,
&version);
if (version != 2)
return 1;
return 0;
}
int main(int argc, char *argv[])
{
char wrapping_salt[TSE_SALT_SIZE];
char *expected_decrypted_passphrase, *filename, *wrapping_passphrase,
*wrapping_salt_hex;
int rc;
if (argc != 5) {
usage(argv[0]);
return EINVAL;
}
filename = argv[1];
expected_decrypted_passphrase = argv[2];
wrapping_passphrase = argv[3];
wrapping_salt_hex = argv[4];
if (strlen(expected_decrypted_passphrase) > TSE_MAX_PASSPHRASE_BYTES ||
strlen(wrapping_passphrase) > TSE_MAX_PASSPHRASE_BYTES ||
strlen(wrapping_salt_hex) != TSE_SALT_SIZE_HEX) {
usage(argv[0]);
return EINVAL;
}
from_hex(wrapping_salt, wrapping_salt_hex, TSE_SALT_SIZE);
rc = verify_unwrap(expected_decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
if (rc)
return 1;
rc = verify_bad_unwrap(expected_decrypted_passphrase, filename,
wrapping_passphrase, wrapping_salt);
if (rc)
return 2;
rc = do_rewrap(filename, wrapping_passphrase, wrapping_salt,
NEW_WRAPPING_PASSPHRASE);
if (rc)
return 3;
rc = verify_unwrap(expected_decrypted_passphrase, filename,
NEW_WRAPPING_PASSPHRASE, NULL);
if (rc)
return 4;
return 0;
}
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe MeetingsApp do
describe 'validations' do
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to validate_presence_of(:description) }
it { is_expected.to validate_presence_of(:start_time) }
it { should validate_uniqueness_of(:start_time) }
it { is_expected.to validate_presence_of(:end_time) }
it { should validate_uniqueness_of(:end_time) }
it { is_expected.to validate_presence_of(:user_id) }
end
describe 'associations' do
it { is_expected.to belong_to(:user) }
end
end
|
import sys
import os
def rot13(text):
def rot13chr(c):
if not ("a" <= c <= "z" or "A" <= c <= "Z"):
return c
offset = ord("A" if c.isupper() else "a")
n = ord(c) - offset
n = (n + 13) % 26
return chr(n + offset)
result = ""
for letter in text:
result += rot13chr(letter)
return result
def read_file(filename):
with open(filename, "r") as f:
return f.read()
def write_file(filename, text):
with open(filename, "w") as f:
f.write(text)
def get_output_filename(filename):
if filename.endswith(".rot13"):
return filename[:-6]
else:
return filename + ".rot13"
def check_overwrite(filename):
if not os.path.isfile(filename):
return True
r = input(filename + " already exists. Overwrite? [yn] ")
return r == "y" or r == "Y"
def usage():
print("usage: " + sys.argv[0] + " <filename>")
sys.exit(1)
def main():
args = sys.argv[1:]
if len(args) != 1:
usage()
input_filename = args[0]
output_filename = get_output_filename(input_filename)
if not os.path.isfile(input_filename):
usage()
check_overwrite(output_filename)
input_str = read_file(input_filename)
output_str = rot13(input_str)
write_file(output_filename, output_str)
if __name__ == "__main__":
main()
|
//
// NetworkService.swift
// SportOn
//
// Created by Marwan Elbahnasawy on 02/05/2023.
//
import Foundation
class NetworkService: NetworkServiceProtocol{
// MARK: Generic fetching data method
static func fetchData(met: String, sportName: String, additionalParam: [String: String] ,completionHandler: @escaping (Data?, URLResponse?, Error?)->Void) {
var urlString = "https://apiv2.allsportsapi.com/\(sportName)/?met=\(met)&APIkey=\(Constants.apiKey)"
for (key,value) in additionalParam{
urlString += "&\(key)=\(value)"
}
guard let url = URL(string: urlString) else{
return
}
let req = URLRequest(url: url)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: req, completionHandler: completionHandler)
task.resume()
}
// MARK: fetching all Leagues
static func fetchLeagues(sportName: String ,completionHandler: @escaping (AllLeaguesResult?)->Void) {
fetchData(met: "Leagues", sportName: sportName, additionalParam: [:]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(AllLeaguesResult.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching upcoming for football/basketball/cricket
static func fetchResultUpcoming(sportName: String, leagueID: String ,completionHandler: @escaping (UpcomingMatchesResultForFootballBasketballCricket?)->Void) {
fetchData(met: "Fixtures", sportName: sportName, additionalParam: ["from":DateUtility.getFromDateString(date: Date()), "to":DateUtility.getToDateString(date: Date(), days: 14), "leagueId":leagueID]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(UpcomingMatchesResultForFootballBasketballCricket.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching upcoming for tennis
static func fetchResultUpcomingTennis(sportName: String, leagueID: String ,completionHandler: @escaping (UpcomingMatchesResultForTennis?)->Void) {
fetchData(met: "Fixtures", sportName: sportName, additionalParam: ["from":DateUtility.getFromDateString(date: Date()), "to":DateUtility.getToDateString(date: Date(), days: 14), "leagueId":leagueID ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(UpcomingMatchesResultForTennis.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching live results for football/basketball/cricket
static func fetchResultLatest(sportName: String, leagueId: String ,completionHandler: @escaping (LiveMatchesResultForFootballBasketballCricket?)->Void) {
fetchData(met: "Livescore", sportName: sportName, additionalParam: ["leagueId":leagueId ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(LiveMatchesResultForFootballBasketballCricket.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching live results for tennis
static func fetchResultLatestTennis(sportName: String, leagueId: String ,completionHandler: @escaping (LiveMatchesResultForTennis?)->Void) {
fetchData(met: "Livescore", sportName: sportName, additionalParam: ["leagueId":leagueId ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(LiveMatchesResultForTennis.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching all teams for a specific league for football/basketball/cricket
static func fetchTeams(sportName: String, leagueId: String ,completionHandler: @escaping (AllTeamsResult?)->Void) {
fetchData(met: "Teams", sportName: sportName, additionalParam: ["leagueId":leagueId ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(AllTeamsResult.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching all players for a specific league for tennis
static func fetchPlayers(sportName: String, leagueId: String ,completionHandler: @escaping (AllPlayersResult?)->Void) {
fetchData(met: "Players", sportName: sportName, additionalParam: ["leagueId":leagueId ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(AllPlayersResult.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching team details for football/basketball/cricket
static func fetchTeam(sportName: String, teamId: String ,completionHandler: @escaping (TeamDetailsResult?)->Void) {
fetchData(met: "Teams", sportName: sportName, additionalParam: ["teamId":teamId ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(TeamDetailsResult.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
// MARK: fetching player details for tennis
static func fetchPlayer(sportName: String, playerId: String ,completionHandler: @escaping (PlayerDetailsResult?)->Void) {
fetchData(met: "Players", sportName: sportName, additionalParam: ["playerId":playerId ]) { data, _, error in
do{
guard let data = data else {return}
let res = try JSONDecoder().decode(PlayerDetailsResult.self, from: data)
completionHandler(res)
} catch let error {
completionHandler(nil)
print(error.localizedDescription)
}
}
}
}
|
import React from 'react';
import TodoListItem from '../todo-list-item';
import './todo-list.css';
const TodoList = ({ data, onDeleted, onToggleDone, onToggleImportant }) => {
const elements = data.map((item) => {
const { id, ...itemProps } = item;
return (
<li
className="list-group-item todo-list-item"
key={id}>
<TodoListItem
{...itemProps}
onDeleted={() => onDeleted(id)}
onToggleDone={() => onToggleDone(id)}
onToggleImportant={() => onToggleImportant(id)} />
</li>
);
});
return (
<ul className="list-group todo-list">
{elements}
</ul>
)
};
export default TodoList;
|
// ignore_for_file: unused_import
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:playon69/Extra/AppTheme.dart';
import 'package:playon69/Extra/CommonFunctions.dart';
import 'package:playon69/Extra/assets.dart';
import 'package:playon69/Screens/DrawerScreen/Web/PaymentMethod.dart';
import 'package:playon69/Screens/DrawerScreen/Web/paymentWebViewScreen.dart';
import 'package:playon69/customs/CustomTextField.dart';
import '../../Models/walletModel.dart';
import '../../apis/callApi.dart';
import '../../apis/sharedPreference.dart';
class addcash extends StatefulWidget {
const addcash({super.key});
@override
State<addcash> createState() => _addcashState();
}
class _addcashState extends State<addcash> {
List<int> price = [100, 200, 500, 1000];
int index = 0;
String? userId;
WalletModel? walletModel;
bool isLoading = true;
getUser() async{
var res = await retrivePref(method: methods.Maps, key: 'currentUser');
userId = res['user_data']['user_name'];
setState(() {});
}
getWallet() async{
var res = await retrivePref(method: methods.Maps, key: 'currentUser');
walletModel = await getWalletDetails1(context, res['token'], res['user_data']['user_name']);
if(walletModel!.status==true){
setState(() {
isLoading = false;
});
}
}
@override
void initState() {
super.initState();
getUser();
getWallet();
}
TextEditingController amt = TextEditingController(text: '0.0');
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text('Add Cash',
style: TextStyle(
fontSize: 14,
fontFamily: font
)
),
backgroundColor: appBarColor,
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: ImageIcon(AssetImage(backicon))
),
titleSpacing: -4,
),
body: isLoading == false ? Column(
children: [
Container(
padding: EdgeInsets.all(15),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
Text('Total Available Balance',
style: TextStyle(
fontFamily: font,
fontSize: 16,
color: textColor2
),
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(coin,height: 15,),
SizedBox(width: 10,),
Text('${walletModel!.walletInfo!.walletAmount}',
style: TextStyle(
fontFamily: font,
color: textColor5,
fontWeight: FontWeight.bold,
fontSize: 18
),
),
],
)
],
)
],
),
),
Expanded(
child: Container(
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
color: upComingBg,
borderRadius: BorderRadius.only(
topRight: Radius.circular(30),
topLeft: Radius.circular(30)
)
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomTextField(
font: font,
fontColor: textColor4,
fontSize: 12,
radiusSize: 10,
paddingSize: EdgeInsets.all(10),
label: 'Amount to add',
widget: TextFormField(
validator: (data){
if(data==null){
return 'Amount to add';
}
return null;
},
decoration: InputDecoration(
//prefix: Image.asset(coin,height: 20,),
border: InputBorder.none,
hintText: 'Amount to add',
hintStyle: TextStyle(
fontFamily: font
)
),
controller: amt,
)
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('(Rs. 25 to Rs. 10,000)',
style: TextStyle(
fontFamily: font,
color: textColor4,
fontSize: 11
),
)
],
),
SizedBox(height: 30,),
Text('Or Select one of the amounts from below',
style: TextStyle(
fontFamily: font,
fontSize: 16,
fontWeight: FontWeight.bold,
color: textColor2
),
),
SizedBox(
height: 5,
),
Text('Use UPI/Bank Transfer when you withdraw more then Rs.',
style: TextStyle(
fontFamily: font,
fontSize: 12,
color: textColor4
),
),
SizedBox(height: 30,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
for(int x=0; x<price.length; x++)
InkWell(
onTap: (){
amt.text = price[x].toString();
},
child: Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: tileBgColor,
borderRadius: BorderRadius.all(
Radius.circular(5)
)
),
child: Row(
children: [
Image.asset(coin,height: 15,),
SizedBox(width: 10,),
Text('${price[x]}',
style: TextStyle(
fontFamily: font,
fontSize: 14,
color: textColor2
),
)
],
),
),
),
],
),
SizedBox(height: 40,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
InkWell(
onTap: (){
setState(() {
index = 0;
});
},
child: Container(
width: width(context, 0.35),
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: tileBgColor,
borderRadius: BorderRadius.all(
Radius.circular(10)
),
border: Border.all(
width: 2,
color: index==0 ? borderColor2 : borderColor
)
),
child: Column(
children: [
SvgPicture.asset(upi),
SizedBox(height: 10,),
Text('Pay Using UPI',
style: TextStyle(
fontFamily: font,
fontSize: 14,
color: textColor2
),
)
],
),
),
),
InkWell(
onTap: (){
setState(() {
index = 1;
});
},
child: Container(
width: width(context, 0.35),
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: tileBgColor,
borderRadius: BorderRadius.all(
Radius.circular(10)
),
border: Border.all(
width: 2,
color: index==1 ? borderColor2 : borderColor
)
),
child: Column(
children: [
Image.asset(creditCard,
height: 30,
),
SizedBox(height: 5,),
Text('Credit/Debit Card',
style: TextStyle(
fontFamily: font,
fontSize: 14,
color: textColor2
),
)
],
),
),
),
],
)
],
),
),
)
],
) : Center(child: CircularProgressIndicator()),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: InkWell(
onTap: (){
if(double.parse(amt.text)>0.0){
if(index==0){
Navigator.push(context, MaterialPageRoute(builder: (ctx) => PaymentWebviewScreen(title: 'UPI Payment',endPoint: 'externalUpiPayment?user_id=$userId&amount=${amt.text}',)));
}else{
Navigator.push(context, MaterialPageRoute(builder: (ctx) => PaymentMethod(amt: amt.text,)));
}
}else{
Fluttertoast.showToast(msg: 'Please enter amount');
}
},
child: Container(
height: height(context, 0.06),
width: width(context, 0.9),
alignment: Alignment.center,
padding: EdgeInsets.only(
top: 15,
bottom: 15
),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)
),
color: buttonBgColor
),
child: Text('Pay Now',
style: TextStyle(
fontFamily: font,
color: textColor1
),
),
),
)
);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
console.log(Math.abs(1));
console.log(Math.abs(-1));
console.log(Math.abs('-1')); //隐式转换
console.log(Math.abs('pink')); //NaN;
// 2.三个取整
// (1) Math.floor() 向下取整 往最小值取
console.log(Math.floor(1.3)); //1
console.log(Math.floor(1.9)); //1
// (2)Math.ceil 向上取整 往最大值取
console.log(Math.ceil(2));
console.log(Math.ceil(2.3)); //3
console.log(Math.ceil(2.8)); //3
// (2)Math.round 四舍五入 5入往大了取
console.log(Math.round(1.2)); //1
console.log(Math.round(1.5)); //2
console.log(Math.round(1.9)); //2
console.log(Math.round(-1.1)); //-1
console.log(Math.round(-1.5)); //这个结果是-1
</script>
</body>
</html>
|
import socket
import time
import numpy as np
from colored_printed import print_colored
class Arm:
_ip: str = '10.10.0.14'
_port: int = 30003
_client: socket.socket
def __init__(self, ip: str = None, port: int = None) -> None:
self._port = port or self._port
self._ip = ip or self._ip
print_colored(f'Connecting to arm at {self._ip}:{self._port}...','cyan')
self.__connect()
def __connect(self) -> None:
self._client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._client.connect((self._ip, self._port))
print_colored('Connected to arm.','cyan')
def __send(self, cmd: str):
self._client.send(f'{cmd}\n'.encode(encoding='utf-8', errors='ignore'))
def movej(
self,
x: float = 0,
y: float = 0,
z: float = 0,
rx: float = 0,
ry: float = 0,
rz: float = 0,
acceleration: float = 1,
velocity: float = 0.75,
task_time: float = 0,
blend_radius: float = 0,
relative = True,
):
if relative:
move_cmd = f'movej(pose_add(get_actual_tcp_pose(),p[{x},{y},{z},{rx},{ry},{rz}]),{acceleration},{velocity},{task_time},{blend_radius})'
else:
move_cmd = f'movej(p[{x},{y},{z},{rx},{ry},{rz}],{acceleration},{velocity},{task_time},{blend_radius})'
print_colored(f'Sending move command: {move_cmd}','cyan')
self.__send(move_cmd)
time.sleep(task_time or 1)
def movel(
self,
x: float = 0,
y: float = 0,
z: float = 0,
rx: float = 0,
ry: float = 0,
rz: float = 0,
acceleration: float = 1,
velocity: float = 0.75,
task_time: float = 0,
blend_radius: float = 0,
relative = True,
):
if relative:
move_cmd = f'movel(pose_add(get_actual_tcp_pose(),p[{x},{y},{z},{rx},{ry},{rz}]),{acceleration},{velocity},{task_time},{blend_radius})'
else:
move_cmd = f'movel(p[{x},{y},{z},{rx},{ry},{rz}],{acceleration},{velocity},{task_time},{blend_radius})'
print_colored(f'Sending move command: {move_cmd}','cyan')
self.__send(move_cmd)
time.sleep(task_time or 1)
def standby_pos(self):
self.movej(x=.046, y=-.32, z=.065, rx=2.2, ry=2.24, rz=0, task_time=2, relative=False)
print_colored('Arm moving to standby position...','cyan')
def home_pos(self):
# self._client.send(b'movel(p[.116,-.3,.2,0,-3.143,0],0.2,0.2,2,0)\n')
# self.movej(x=.116, y=-.3, z=.2, rx=0, ry=-3.143, rz=0, task_time=1, relative=False)
angles = (np.array([-48.48, -101.48, -40.23, -128.24, 90.05, 41.52])*np.pi/180).astype(str)
move_cmd = f'movej([{",".join(angles)}],1,1,2,0)'
self.__send(move_cmd)
print_colored('Arm moving to home position...','cyan')
if __name__ == '__main__':
arm = Arm()
# arm.home_pos()
arm.standby_pos()
|
import { Lerp } from "./lerp.js"
export enum AcceleratorDirection {
Forward = 'forward',
Backward = 'backward',
Stop = 'stop'
}
export type AcceleratorSettings = {
maxSpeed?: number,
accelerationRate?: number,
startingSpeed?: number,
direction?: AcceleratorDirection
}
export class Accelerator {
maxSpeed: number
direction: AcceleratorDirection
lerp: Lerp
constructor(startingSpeed:number = 0, maxSpeed: number = 0, accelerationRate: number = .01, direction: AcceleratorDirection = AcceleratorDirection.Stop) {
this.maxSpeed = maxSpeed
this.lerp = new Lerp(startingSpeed, maxSpeed, accelerationRate)
this.setDirection(direction)
}
getCurrentLerpTarget(){
return this.lerp.destination
}
run() {
return this.lerp.run()
}
reset() {
this.lerp.reset()
}
setDirection(newDirection: AcceleratorDirection) {
if(newDirection === this.direction) return
switch(newDirection) {
case AcceleratorDirection.Forward:
this.lerp.redirect(this.maxSpeed)
break;
case AcceleratorDirection.Backward:
this.lerp.redirect(-this.maxSpeed)
break;
case AcceleratorDirection.Stop:
this.lerp.redirect(0)
break;
default:
throw new Error(`Accelerator was given an unacceptable direction: ${newDirection}`)
}
this.direction = newDirection
}
}
|
import { useResponsiveApi } from "../../App";
import Banner from "../../components/Banner";
import Content2 from "../../components/Content2";
import Content3 from "../../components/Content3";
import Footer from "../../components/Footer";
import LeftMenu from "../../components/LeftMenu";
import css from "../../css/Contents.css";
import baemin from "../../images/fe_baemin.png";
export default function FrontendM(){
var {isMobile} = useResponsiveApi();
return (<>
<Banner></Banner>
<div className="simpleflex">
{isMobile?<div></div>:<LeftMenu></LeftMenu>}
<div className="contenttext">
<h1>- 프론트엔드 개발자</h1><br/>
웹 디자이너가 디자인에 대한 뼈대를 잡으면 <br/>
퍼블리셔가 디자인에 관한 내용을 채워줍니다. <br/><br/>
그러면 프론트엔드 개발자는 <br/>
이렇게 설계된 디자인에 대한 효과를 넣어줍니다. <br/><br/>
즉, 웹페이지의 전면부 효과를 개발하는 역할입니다.<br/><br/>
최근에는 퍼블리셔와 프론트엔드 개발자의 경계가 모호해지고 있습니다.<br/>
외국은 퍼블리셔의 개념 자체가 없다고 말하기도 합니다.<br/><br/>
프론트엔드 개발자는 버튼을 누르면 <br/>
메뉴가 스르륵 나온다던지, <br/>
글씨가 이동한다던지, <br/>
스크롤바를 돌리면 사진이 유동적으로 움직인다던지 <br/>
등의 기능을 요구에 따라 넣어줍니다. <br/><br/>
배달의 민족 홈페이지에 들어갔을 때 <br/>
스크롤 바를 움직이면 <br/>
페이지 단위로 사진이 넘어가는 것이 <br/>
대표적인 예시입니다.<br/>
<div className="tech1">
<img src={baemin} alt="baemin"></img>
</div>
프론트엔드 개발자들의 작업은 <br/>
보통 인터넷 익스플로러나 구글 크롬을 열고서 <br/>
F12 키를 누르면 보이는 소스코드로 확인할 수 있습니다. <br/><br/>
보안이 철저한 기업일수록 <br/>
화면에 뿌려지는 소스코드만 노출하고<br/>
계산이 되거나 효과가 보이는 소스코드는 <br/>
노출시키지 않습니다.<br/><br/>
왜냐하면, 이렇게 노출되는 계산 소스코드를 악용하여<br/>
해킹에 이용되기도 하기 때문입니다. <br/><br/>
프론트엔드에 대한 취업을 원하시거나 <br/>
학습하기를 원하시는 분께서는 HTML, CSS에 대한 학습은 필수입니다. <br/>
HTML과 CSS는 단순하게 웹 브라우저에 글씨나 <br/>
표, 그림을 보여주고 꾸며주는 역할을 합니다. <br/>
그리고 이렇게 꾸며진 것을 다양하게 효과를 주기 위한 기술로 <br/>
<b>Javascript, React, Vue.js</b> 등의 기술이 있습니다.
</div>
</div>
{isMobile?<div><Content2></Content2><Content3></Content3></div>:<div></div>}
<Footer></Footer>
</>)
}
|
@extends('layouts.app')
@section('title', $title)
@push('before-style')
@endpush
@section('content')
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0">Data Siswa/i</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="{{ route('admin.dashboard.index') }}">Dashboard</a></li>
<li class="breadcrumb-item active">Data Siswa/i</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<div class="btn-group mb-5">
<a href="{{ route('admin.siswa.create') }}" class="btn btn-success btn-sm font-weight-bold"><i class="fa fa-plus-circle mr-2"></i>Tambah Data</a>
</div>
<div class="table-responsive">
<table id="siswa" class="table table-striped table-bordered" style="width: 100%">
<thead class="text-center">
<tr>
<th class="text-center">No</th>
<th class="text-center">Aksi</th>
<th class="text-center">Nama Lengkap</th>
<th class="text-center">NISN</th>
<th class="text-center">NIK</th>
<th class="text-center">Jenis Kelamin</th>
<th class="text-center">TTL</th>
<th class="text-center">Email</th>
<th class="text-center">No Telp</th>
<th class="text-center">Tahun Daftar</th>
<th class="text-center">Profile</th>
</tr>
</thead>
<tbody class="text-center">
@php
$n=1;
@endphp
@foreach ($data as $d)
<tr>
<td>{{ $n; }}</td>
<td>
<div class="btn-group">
<a href="{{ route('admin.siswa.edit', $d->id) }}" class="btn btn-warning btn-sm"><i class="fa fa-pencil-alt"></i></a>
<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#hapus{{ $d->id }}"><i class="fa fa-trash-alt"></i></button>
</div>
<div class="modal fade" id="hapus{{ $d->id }}" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-danger">
<h5 class="modal-title font-weight-bold" id="staticBackdropLabel">Konfirmasi Hapus</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<div class="alert alert-info">
<h5>Apakah anda yakin akan menhapus akun dengan nama : <span class="font-weight-bold">{{ $d->nama_lengkap }}</span></h5>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button>
<form action="{{ route('admin.siswa.destroy', $d->id) }}" method="POST" enctype="multipart/form-data">
@csrf
@method('DELETE')
<button class="btn btn-danger btn-sm" type="submit">Hapus</button>
</form>
</div>
</div>
</div>
</div>
</td>
<td>{{ $d->nama_lengkap }}</td>
<td>{{ $d->nisn }}</td>
<td>{{ $d->nik }}</td>
<td>{{ $d->jenis_kelamin }}</td>
<td>{{ $d->tmp_lahir }}, {{ $d->tgl_lahir->format('d, M Y') }}</td>
<td>{{ $d->email }}</td>
<td>{{ $d->no_telp }}</td>
<td>{{ $d->thn_daftar }}</td>
<td>
@if ($d->foto_profile == null)
<span class="badge badge-danger">Belum Upload</span>
@else
<img src="{{ Storage::url($d->foto_profile) }}" class="img-fluid rounded" alt="profile" width="50%">
@endif
</td>
</tr>
@php
$n++;
@endphp
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
@endsection
@push('after-script')
<script>
$(document).ready(function () {
$('#siswa').DataTable();
});
</script>
@endpush
|
import {GifItem} from './GifItem';
import {useFetchGifs} from '../hooks/useFetchGifs';
// Este componente muestra lo buscado en el HTML
export const GifGrid = ({category}) => {
// Custom hook para mostrar mensaje de carga
const {images, isLoading} = useFetchGifs(category);
// console.log({images, isLoading});
return (
<>
<h3>{category}</h3>
{/* Mostramos mensaje de carga si 'isLoading' está en 'true' */}
{
isLoading && <h2>Cargando...</h2>
}
<div className='card-grid'>
{
images.map((image) => (
<GifItem
key={image.id}
{...image}
/>
))
}
</div>
</>
);
};
|
import { useState, useEffect } from 'react';
function BucketSortVisualizer() {
const [mainArray, setMainArray] = useState([]);
const [buckets, setBuckets] = useState(new Array(5).fill().map(() => []));
const [sorting, setSorting] = useState(false)
const generateArray = (size, max) => {
const newArray = [];
for (let i = 0; i < size; i++) {
newArray.push(Math.floor(Math.random() * max) + 1);
}
setMainArray(newArray);
setBuckets(new Array(5).fill().map(() => []));
};
useEffect(() => {
generateArray(20, 20);
}, []);
function bucketSorting() {
setSorting(true)
let array = [...mainArray];
let noOfBuckets = 5
let maxElement = Math.max(...array);
let minElement = Math.min(...array);
let Range = (maxElement - minElement) / noOfBuckets;
let temp = [];
for (let i = 0; i < noOfBuckets; i++) {
temp.push([]);
}
for (let i = 0; i < array.length; i++) {
let diff = (array[i] - minElement) / Range - Math.floor((array[i] - minElement) / Range);
if (diff === 0 && array[i] !== minElement) {
temp[Math.floor((array[i] - minElement) / Range) - 1].push(array[i]);
} else {
temp[Math.floor((array[i] - minElement) / Range)].push(array[i]);
}
}
setBuckets(temp)
for (let i = 0; i < temp.length; i++) {
if (temp[i].length !== 0) {
temp[i].sort((a, b) => a - b);
}
}
setBuckets(temp)
let k = 0;
for (let lst of temp) {
if (lst.length) {
for (let i of lst) {
array[k] = i;
k++;
}
}
}
let i = 0;
const intervalId = setInterval(() => {
setMainArray(array.slice(0, i + 1));
i++;
if (i >= array.length) {
clearInterval(intervalId);
setSorting(false)
}
}, 800);
}
return (
<>
<div className="container-fluid py-5 min-vh-100 d-flex flex-column justify-content-between">
<div>
<button className="mx-lg-5 btn btn-outline-primary" onClick={() => generateArray(20, 20)} disabled={sorting}>Generate Array</button>
<button className="mx-lg-5 btn btn-outline-primary" onClick={bucketSorting} disabled={sorting}>Sort Array</button>
</div>
<div className="animate__animated" style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-end' }}>
{mainArray.map((num, idx) => (
<div key={idx} className="animate__animated animate__zoomIn" style={{ backgroundColor: '#6ec4ff', height: `${(num * 3) + 40}px`, width: '30px', margin: '2px', position: "relative" }}>
<p style={{
position: "absolute",
bottom: "-20px",
margin: "0",
fontSize: "12px",
left: "50%",
transform: "translateX(-50%)"
}}>
{num}
</p>
</div>
))}
</div>
<div class="container-fluid">
<div class="row justify-content-center align-items-start" >
<div class="col-12 mb-4">
<div class="table-responsive">
<table class="table table-dark table-bordered text-center table-futuristic">
<tbody>
<tr>
<th>Buckets</th>
{/*<!-- Iterate over 'buckets' array -->*/}
{buckets.map((values, i) => (
<td key={i}>{i}</td>
))}
</tr>
<tr>
<th>Elements</th>
{/*<!-- Iterate over 'buckets' array -->*/}
{buckets.map((values, i) => (
<td key={i}>
{/*<!-- Iterate over 'values' array in each 'bucket' -->*/}
{values.map((value, j) => (
<div key={j}>{value}</div>
))}
</td>
))}
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8">
<h2 class="h2">Bucket Sort</h2>
<p class="fs-6">
One such algorithm that stands out for its simplicity and efficiency is Bucket Sort. By distributing elements into different buckets and sorting them individually, Bucket Sort provides an elegant solution for sorting a large set of numbers. In this article, we will explore the step-by-step process of Bucket Sort using a real-life example and an array of numbers. Additionally, we will discuss the time and space complexities of this algorithm.
</p>
<h5 class="h5">
Overview:
</h5>
<p class="fs-6">
Bucket Sort operates on the principle of dividing the input array into several smaller buckets. Each bucket represents a subrange of values from the original array. The elements are then distributed into their respective buckets based on their value ranges. Finally, the individual buckets are sorted, and the sorted elements are concatenated to obtain the final sorted array.
</p>
<h5 class="h5">
Step-by-Step Explanation:
</h5>
<p class="fs-6">
To better comprehend the Bucket Sort algorithm, let's consider an example of sorting a set of student scores in a class.
<br /><br />
Example: <br />
Suppose we have an array of student scores: [92, 85, 78, 95, 88, 82, 91, 85, 90, 89].
<br /><br />
Step 1: Creating Buckets: <br />
We start by creating a fixed number of buckets, each representing a specific range of values. In this case, let's create ten buckets, each representing a range of ten scores. The ranges could be: [0-9], [10-19], [20-29], and so on, until [90-99].
<br /><br />
Step 2: Distributing Elements: <br />
Next, we distribute the student scores into their respective buckets based on their range. For our example, the distribution would be as follows:
<br /> <br />
Bucket 0-9: Empty <br />
Bucket 10-19: Empty <br />
Bucket 20-29: Empty <br />
Bucket 30-39: Empty <br />
Bucket 40-49: Empty <br />
Bucket 50-59: Empty <br />
Bucket 60-69: Empty <br />
Bucket 70-79: [78] <br />
Bucket 80-89: [85, 82, 85, 88, 82, 89] <br />
Bucket 90-99: [92, 95, 91, 90]
<br /><br />
Step 3: Sorting Individual Buckets: <br />
After distributing the elements into their respective buckets, we sort each bucket individually. In our example:
<br /><br />
Bucket 0-9: Empty <br />
Bucket 10-19: Empty <br />
Bucket 20-29: Empty <br />
Bucket 30-39: Empty <br />
Bucket 40-49: Empty <br />
Bucket 50-59: Empty <br />
Bucket 60-69: Empty <br />
Bucket 70-79: [78] <br />
Bucket 80-89: [82, 85, 85, 88, 89] <br />
Bucket 90-99: [90, 91, 92, 95]
<br /><br />
Step 4: Concatenating Buckets: <br />
Finally, we concatenate the sorted buckets to obtain the final sorted array. In our example:
<br /><br />
Sorted Array: [78, 82, 85, 85, 88, 89, 90, 91, 92, 95]
</p>
<h5 class="h5">
Conclusion:
</h5>
<p class="fs-6">
Bucket Sort is an efficient sorting algorithm that works well when the input elements are uniformly distributed. By dividing the data into separate buckets, sorting them individually, and then concatenating them, Bucket Sort provides a relatively simple and effective way to sort large sets of numbers. Its time complexity of O(n + k^2) makes it suitable for scenarios where the range of values is limited. However, it's important to note that the performance of Bucket Sort can be influenced by the choice of the underlying sorting algorithm for sorting individual buckets.
</p>
</div>
<div class="col-lg-4">
<h2 class="h2">Complexities</h2>
<table class="table table-dark table-hover table-bordered text-center table-futuristic">
<thead>
<tr>
<th scope="col">Scenario</th>
<th scope="col">Time Complexity</th>
<th scope="col">Space Complexity</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="col">Best case</th>
<td>O(n + k)</td>
<td>O(n + k)</td>
</tr>
<tr>
<th scope="col">Worst case</th>
<td>O(n^2)</td>
<td>O(n + k)</td>
</tr>
<tr>
<th scope="col">Average case</th>
<td>O(n + n^2/k + k)</td>
<td>O(n + k)</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</>
);
}
export default BucketSortVisualizer;
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BaseComponent } from './views/layout/base/base.component';
import { AuthGuard } from './core/guard/auth.guard';
import { ErrorPageComponent } from './views/pages/error-page/error-page.component';
import { BaseClientComponent } from './views/layout/dashboardclient/baseclient/baseclient.component';
import { BaseAdminComponent } from './views/layout/dashboardadmin/baseadmin/baseadmin.component';
import { BaseChauffeurComponent } from './views/layout/dashboardchauffeur/basechauffeur/basechauffeur.component';
import { ListclientComponent } from './views/pages/admin/listclient/listclient.component';
import { ListvehiculeComponent } from './views/pages/admin/listvehicule/listvehicule.component';
import { ListcamionComponent } from './views/pages/admin/listcamion/listcamion.component';
import { ListdemandesComponent } from './views/pages/admin/listdemandes/listdemandes.component';
import { ListchauffeurComponent } from './views/pages/admin/listchauffeur/listchauffeur.component';
import { GeolocalisationComponent } from './views/pages/admin/geolocalisation/geolocalisation.component';
import { HistoriqueComponent } from './views/pages/admin/historique/historique.component';
import { MesVehiculesComponent } from './views/pages/client/mes-vehicules/mes-vehicules.component';
import { MesdemandesComponent } from './views/pages/client/mesdemandes/mesdemandes.component';
import { MesmissionComponent } from './views/pages/chauffeur/mesmission/mesmission.component';
import { MesclientComponent } from './views/pages/chauffeur/mesclient/mesclient.component';
import { MescamionComponent } from './views/pages/chauffeur/mescamion/mescamion.component';
import { GeoChauffuerComponent } from './views/pages/chauffeur/geochauffuer/geochauffuer.component';
import { HistoriqueChauffeurComponent } from './views/pages/chauffeur/historiquechauffeur/historiquechauffeur.component';
import { GeoClientComponent } from './views/pages/client/geoclient/geoclient.component';
import { HistoriqueClientComponent } from './views/pages/client/historiqueclient/historiqueclient.component';
import { EditProfileComponent } from './views/pages/editprofile/editprofile.component';
import { EditcamionComponent } from './views/pages/editcamion/editcamion.component';
import { EditClientComponent } from './views/pages/edit-client/edit-client.component';
import { EditChauffeurComponent } from './views/pages/edit-chauffeur/edit-chauffeur.component';
import { EditVoitureComponent } from './views/pages/edit-voiture/edit-voiture.component';
import { EditUserProfileComponent } from './views/pages/edit-user-profile/edit-user-profile.component';
const routes: Routes = [
{ path:'auth', loadChildren: () => import('./views/pages/auth/auth.module').then(m => m.AuthModule) },
/* {
path: '',
component: BaseComponent,
canActivate: [AuthGuard],
children: [
{
path: 'dashboard',
loadChildren: () => import('./views/pages/dashboard/dashboard.module').then(m => m.DashboardModule)
},
// { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
// { path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
]
},*/
{
path: 'client',
component: BaseClientComponent,
// canActivate: [AuthGuard],
children: [
{
path: '',
loadChildren: () => import('./views/layout/dashboardclient/clienthome/clienthome.module').then(m => m.ClientHomeModule)
},
{ path: 'mesvehicules',component: MesVehiculesComponent},
{ path: 'mesdemandes',component: MesdemandesComponent},
{ path: 'geolocalisation',component: GeoClientComponent},
{ path: 'historique',component: HistoriqueClientComponent},
{ path: 'edit/:id',component: EditClientComponent},
]
},
{
path: 'admin',
component: BaseAdminComponent,
// canActivate: [AuthGuard],
children: [
{
path: '',
loadChildren: () => import('./views/layout/dashboardadmin/adminhome/adminhome.module').then(m => m.AdminHomeModule)
},
{ path: 'listclient',component: ListclientComponent},
{ path: 'listvehicule',component: ListvehiculeComponent},
{ path: 'listcamion',component: ListcamionComponent},
{ path: 'listdemandes',component: ListdemandesComponent},
{ path: 'listchauffeur',component: ListchauffeurComponent},
{ path: 'geolocalisation',component: GeolocalisationComponent},
{ path: 'historique',component: HistoriqueComponent},
{ path: 'edit/:id',component: EditClientComponent},
{ path: 'editcamion/:id',component: EditcamionComponent},
{ path: 'editChauffeur/:id',component: EditChauffeurComponent},
{ path: 'editVoiture/:id',component: EditVoitureComponent},
{ path: 'editUserProfile',component: EditUserProfileComponent},
]
},
{
path: 'chauffeur',
component: BaseChauffeurComponent,
//canActivate: [AuthGuard],
children: [
{
path: '',
loadChildren: () => import('./views/layout/dashboardchauffeur/chauffuerhome/chauffuerhome.module').then(m => m.ChauffuerHomeModule)
},
{ path: 'mesmission',component: MesmissionComponent},
{ path: 'mesclient',component: MesclientComponent},
{ path: 'mescamion',component: MescamionComponent},
{ path: 'geolocalisation',component: GeoChauffuerComponent},
{ path: 'historique',component: HistoriqueChauffeurComponent},
{ path: 'edit/:id',component: EditProfileComponent},
]
},
{ path: '', redirectTo: 'admin', pathMatch: 'full' },
{
path: 'error',
component: ErrorPageComponent,
data: {
'type': 404,
'title': 'Page Not Found',
'desc': 'Oopps!! The page you were looking for doesn\'t exist.'
}
},
{
path: 'error/:type',
component: ErrorPageComponent
},
{ path: '**', redirectTo: 'error', pathMatch: 'full' },
{ path: 'edit/:id',component: EditProfileComponent},
{ path: 'editcamion/:id',component: EditcamionComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'top' })],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style rel="stylesheet" type="text/css">
/*
+ 다음형제
~ 다음형제요소들
> 자식요소
(띄어쓰기) 자손요소
*/
h1,h2{ /*자식이 첫번째인 li*/
color:red;
}
</style>
</head>
<body>
<h1>태그선택자를 이용한</h1>
<h2>제어</h2>
<p>p1</p>
<p>p2</p>
<h2>제어</h2>
<p>p3</p>
<p>p4</p>
<ul>
<li>item1<a href="#">link</a></li>
<li>item2<a href="#">link</a></li>
<li>item3<a href="#">link</a></li>
<li>item4<a href="#">link</a></li>
</ul>
<ol>
<li>item1<a href="#">link</a></li>
<li>item2<a href="#">link</a></li>
<li>item3<a href="#">link</a></li>
<li>item4<a href="#">link</a></li>
</ol>
<tbody>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tr>
<td>item1</td>
<td>item1</td>
<td>item1</td>
</tr>
<tbody>
<tr>
<td>item2</td>
<td>item2</td>
<td>item2</td>
</tr>
<tr>
<td>item3</td>
<td>item3</td>
<td>item3</td>
</tr>
<tr>
<td>item4</td>
<td>item4</td>
<td>item4</td>
</tr>
<tr>
<td>item5</td>
<td>item5</td>
<td>item5</td>
</tr>
<tr>
<td>item6</td>
<td>item6</td>
<td>item6</td>
</tr>
</tbody>
</table>
</body>
</html>
|
# Copyright (c) 2024, Tariq Siddique and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.utils import flt
from hsms.controllers.hsms_controller import HSMS_Controller, validate_accounting_period_open
class MemberNOC(HSMS_Controller):
def validate(self):
self.validate_posting_date()
validate_accounting_period_open(self)
self.validate_noc_type()
self.validate_net_amount()
def on_submit(self):
self.make_gl_entries()
def validate_noc_type(self):
noc_types = []
for row in self.noc_item:
payment_type = row.noc_type
if payment_type in noc_types:
frappe.throw(_("Payment Type '{0}' occurs more than once").format(payment_type))
else:
noc_types.append(payment_type)
def validate_net_amount(self):
if self.net_amount <=0:
frappe.throw(_("Net Amount not less then zero "))
def make_gl_entries(self):
if self.net_amount != 0:
company = frappe.get_doc("Company", self.company)
default_receivable_account = frappe.get_value("Company", company, "default_receivable_account")
noc_account = frappe.get_value("Company", self.company, "default_noc_revenue_account")
if not default_receivable_account:
frappe.throw('Please set Default Receivable Account in Company Settings')
if not noc_account:
frappe.throw('Please set Default NOC Account in Company Settings')
cost_center = frappe.get_value("Company", self.company, "real_estate_cost_center")
if not cost_center:
frappe.throw('Please set Cost Centre in Company Settings')
journal_entry = frappe.get_doc({
"doctype": "Journal Entry",
"voucher_type": "Journal Entry",
"voucher_no": self.name,
"posting_date": self.posting_date,
"user_remark": self.remarks,
"document_number": self.name,
"document_type": "Member NOC",
"property_number": self.property_number
})
journal_entry.append("accounts", {
"account": default_receivable_account,
"party_type": "Customer",
"party": self.customer,
"debit_in_account_currency": self.net_amount,
"property_number": self.property_number,
"cost_center": "",
"is_advance": 0,
"document_number": self.name,
"document_type": "Member NOC"
})
journal_entry.append("accounts", {
"account": noc_account,
"credit_in_account_currency": self.net_amount,
"against": default_receivable_account,
"property_number": self.property_number,
"cost_center": cost_center,
"is_advance": 0,
"document_number": self.name,
"document_type": "Member NOC"
})
journal_entry.insert(ignore_permissions=True)
journal_entry.submit()
frappe.db.commit()
frappe.msgprint(_('Journal Entry {0} created successfully').format(frappe.get_desk_link("Journal Entry", journal_entry.name)))
|
<template>
<div class="header-view">
<!-- 左侧icon图标 -->
<div class="left-part">
<el-button icon="el-icon-s-fold" size="mini" @click="tapMenu"></el-button>
<span>控制台</span>
</div>
<div class="right-part">
<!-- 右侧头像和用户名 -->
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link">
<router-link to="/login"><img :src="avatar.Header" class="user" /></router-link>
{{ avatar.Name }}
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="a">个人中心</el-dropdown-item>
<el-dropdown-item command="b">设置</el-dropdown-item>
<el-dropdown-item command="c">退出</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
computed: {
...mapState({
// 映射的用户数据
user: (state) => state.user,
}),
// 头像和用户名逻辑
avatar() {
return this.user
? this.user
: {
Name: "未登录",
Header:
"https://img0.baidu.com/it/u=1240274933,2284862568&fm=253&fmt=auto&app=138&f=PNG?w=180&h=180",
};
},
},
methods: {
// 退出提示框
open() {
this.$confirm("确定退出吗?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
})
.then(() => {
this.$router.replace("/login");
this.logoutRemove()
})
.catch(() => { });
},
...mapMutations({
// 映射切换左侧导航栏展开与折叠的方法
Collapse_Menu: "collapse/Collapse_Menu",
logoutRemove: 'logoutRemove'
}),
// 切换左侧导航栏展开与折叠
tapMenu() {
this.Collapse_Menu();
},
handleCommand(command) {
// this.$message("click on item " + command);
// 退出登录
command === "c" ? this.open() : undefined;
command === "b"
? this.$route.path !== "/main/system"
? this.$router.push("/main/system")
: undefined
: undefined;
},
},
};
</script>
<style scoped lang="less">
.header-view {
background-color: skyblue;
height: 60px;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 5px;
// 左侧部分
.left-part {
display: flex;
align-items: center;
.el-button {
background-color: skyblue;
border: none;
}
.el-button--mini {
font-size: 26px;
}
}
// 右侧部分
.right-part {
// 用户名样式
.el-dropdown-link {
cursor: pointer;
color: #2941e4;
font-weight: 600;
}
// 头像样式
.user {
width: 36px;
height: 36px;
border-radius: 50%;
margin-right: 5px;
vertical-align: middle;
}
}
// // 自定义icon图标
// .el-icon-my-export {
// background: url("@/assets/image/logo.png") center no-repeat;
// background-size: cover;
// }
// .el-icon-my-export:before {
// content: "替";
// font-size: 16px;
// visibility: hidden;
// }
// .el-icon-my-export {
// font-size: 16px;
// }
// .el-icon-my-export:before {
// content: "\e611";
// }
}
</style>
|
import React, { useEffect, useState } from 'react'
import Navbar from './Navbar'
import Products from './Products'
import { auth, fs } from '../Config/Config'
import { useNavigate } from 'react-router-dom'
const Home = () => {
const navigate = useNavigate();
// get the current user
function GetCurrentUser() {
const [user, setUser] = useState(null);
useEffect(() => {
auth.onAuthStateChanged(user => {
if (user) {
fs.collection('users').doc(user.uid).get().then(snapshot => {
setUser(snapshot.data().FullName);
})
}
else {
setUser(null);
}
})
}, [])
return user;
}
const user = GetCurrentUser();
console.log(user)
const [products, setProducts] = useState([]);
// getting product functions
const getProducts = async () => {
const products = await fs.collection('Products').get();
const productsArray = [];
for (var snap of products.docs) {
var data = snap.data();
data.ID = snap.id;
productsArray.push({
...data
})
if (productsArray.length === products.docs.length) {
setProducts(productsArray);
}
}
}
useEffect(() => {
getProducts();
}, [])
const [totalProducts, setTotalProducts] = useState(0);
// getting cart products
useEffect(() => {
auth.onAuthStateChanged(user => {
if (user) {
fs.collection('cart' + user.uid).onSnapshot(snapshot => {
const qty = snapshot.docs.length;
setTotalProducts(qty);
})
}
})
},[])
const getUserId = () => {
const [uId, setUId] = useState(null);
useEffect(() => {
auth.onAuthStateChanged(user => {
if (user) {
setUId(user.uid);
}
})
}, [])
return uId;
}
const uId = getUserId();
let Product;
const addToCart = (product) => {
if (uId === null) {
navigate('/login')
} else {
Product = product;
Product['qty'] = 1;
Product['TotalProductPrice'] = Product.qty * Product.price;
fs.collection('cart' + uId).doc(product.ID).set(Product).then(() => {
console.log('successfully added to cart')
})
console.log(product)
console.log('uid', uId)
}
}
return (
<div>
<Navbar user={user} totalProducts={totalProducts} />
{products.length > 0 && (
<div className='container-fluid mt-5'>
<h1 className='text-center'>Products</h1>
<div className='products-box'>
<Products products={products} onAddToCart={addToCart} />
</div>
</div>
)}
{products.length < 1 && (
<div className='container-fluid'>Please Wait........</div>
)}
</div>
)
}
export default Home
|
import { createContext, useReducer } from "react";
export const TitleColorContext = createContext()
export const titleColorReducer = (state, action) => {
switch(action.type) {
case "RED":
return {...state, color: "red"}
case "BLUE":
return { ...state, color: "blue" }
case "PURPLE":
return { ...state, color: "purple" }
default:
return state
}
}
export const TitleColorContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(titleColorReducer, { color: "purple" })
return (
<TitleColorContext.Provider value={{ ...state, dispatch }}>
{children}
</TitleColorContext.Provider>
)
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.calling.di
import android.content.Context
import com.azure.android.communication.ui.calling.CallComposite
import com.azure.android.communication.ui.calling.data.CallHistoryRepositoryImpl
import com.azure.android.communication.ui.calling.error.ErrorHandler
import com.azure.android.communication.ui.calling.getConfig
import com.azure.android.communication.ui.calling.handlers.CallStateHandler
import com.azure.android.communication.ui.calling.handlers.RemoteParticipantHandler
import com.azure.android.communication.ui.calling.logger.DefaultLogger
import com.azure.android.communication.ui.calling.logger.Logger
import com.azure.android.communication.ui.calling.presentation.VideoStreamRendererFactory
import com.azure.android.communication.ui.calling.presentation.VideoStreamRendererFactoryImpl
import com.azure.android.communication.ui.calling.presentation.VideoViewManager
import com.azure.android.communication.ui.calling.presentation.manager.AccessibilityAnnouncementManager
import com.azure.android.communication.ui.calling.presentation.manager.AudioFocusManager
import com.azure.android.communication.ui.calling.presentation.manager.AudioModeManager
import com.azure.android.communication.ui.calling.presentation.manager.AudioSessionManager
import com.azure.android.communication.ui.calling.presentation.manager.AvatarViewManager
import com.azure.android.communication.ui.calling.presentation.manager.CompositeExitManager
import com.azure.android.communication.ui.calling.presentation.manager.CameraStatusHook
import com.azure.android.communication.ui.calling.presentation.manager.DebugInfoManager
import com.azure.android.communication.ui.calling.presentation.manager.DebugInfoManagerImpl
import com.azure.android.communication.ui.calling.presentation.manager.LifecycleManagerImpl
import com.azure.android.communication.ui.calling.presentation.manager.MeetingJoinedHook
import com.azure.android.communication.ui.calling.presentation.manager.MicStatusHook
import com.azure.android.communication.ui.calling.presentation.manager.NetworkManager
import com.azure.android.communication.ui.calling.presentation.manager.ParticipantAddedOrRemovedHook
import com.azure.android.communication.ui.calling.presentation.manager.PermissionManager
import com.azure.android.communication.ui.calling.presentation.manager.SwitchCameraStatusHook
import com.azure.android.communication.ui.calling.presentation.navigation.NavigationRouterImpl
import com.azure.android.communication.ui.calling.redux.AppStore
import com.azure.android.communication.ui.calling.redux.Middleware
import com.azure.android.communication.ui.calling.redux.middleware.CallingMiddlewareImpl
import com.azure.android.communication.ui.calling.redux.middleware.handler.CallingMiddlewareActionHandlerImpl
import com.azure.android.communication.ui.calling.redux.reducer.AppStateReducer
import com.azure.android.communication.ui.calling.redux.reducer.AudioSessionStateReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.CallStateReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.ErrorReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.LifecycleReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.LocalParticipantStateReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.NavigationReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.ParticipantStateReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.PermissionStateReducerImpl
import com.azure.android.communication.ui.calling.redux.reducer.Reducer
import com.azure.android.communication.ui.calling.redux.state.AppReduxState
import com.azure.android.communication.ui.calling.redux.state.ReduxState
import com.azure.android.communication.ui.calling.service.CallingService
import com.azure.android.communication.ui.calling.service.CallHistoryService
import com.azure.android.communication.ui.calling.service.CallHistoryServiceImpl
import com.azure.android.communication.ui.calling.service.NotificationService
import com.azure.android.communication.ui.calling.service.sdk.CallingSDK
import com.azure.android.communication.ui.calling.service.sdk.CallingSDKEventHandler
import com.azure.android.communication.ui.calling.service.sdk.CallingSDKWrapper
import com.azure.android.communication.ui.calling.utilities.CoroutineContextProvider
internal class DependencyInjectionContainerImpl(
private val parentContext: Context,
override val callComposite: CallComposite,
private val customCallingSDK: CallingSDK?,
private val customVideoStreamRendererFactory: VideoStreamRendererFactory?,
private val customCoroutineContextProvider: CoroutineContextProvider?,
) : DependencyInjectionContainer {
override val configuration by lazy {
callComposite.getConfig()
}
override val navigationRouter by lazy {
NavigationRouterImpl(appStore)
}
override val callingMiddlewareActionHandler by lazy {
CallingMiddlewareActionHandlerImpl(
callingService,
coroutineContextProvider
)
}
override val callStateHandler by lazy {
CallStateHandler(configuration, appStore)
}
override val errorHandler by lazy {
ErrorHandler(configuration, appStore)
}
override val videoViewManager by lazy {
VideoViewManager(
callingSDKWrapper,
applicationContext,
customVideoStreamRendererFactory ?: VideoStreamRendererFactoryImpl()
)
}
override val compositeExitManager by lazy {
CompositeExitManager(appStore, configuration)
}
override val permissionManager by lazy {
PermissionManager(appStore)
}
override val audioSessionManager by lazy {
AudioSessionManager(
appStore,
applicationContext,
)
}
override val audioFocusManager by lazy {
AudioFocusManager(
appStore,
applicationContext,
)
}
override val audioModeManager by lazy {
AudioModeManager(
appStore,
applicationContext,
)
}
override val networkManager by lazy {
NetworkManager(
applicationContext,
)
}
override val debugInfoManager: DebugInfoManager by lazy {
DebugInfoManagerImpl(
callHistoryRepository,
)
}
override val callHistoryService: CallHistoryService by lazy {
CallHistoryServiceImpl(
appStore,
callHistoryRepository
)
}
override val avatarViewManager by lazy {
AvatarViewManager(
coroutineContextProvider,
appStore,
configuration.callCompositeLocalOptions,
configuration.remoteParticipantsConfiguration
)
}
override val accessibilityManager by lazy {
AccessibilityAnnouncementManager(
appStore,
listOf(
MeetingJoinedHook(),
CameraStatusHook(),
ParticipantAddedOrRemovedHook(),
MicStatusHook(),
SwitchCameraStatusHook(),
)
)
}
override val lifecycleManager by lazy {
LifecycleManagerImpl(appStore)
}
override val appStore by lazy {
AppStore(
initialState,
appReduxStateReducer,
appMiddleware,
storeDispatcher
)
}
override val notificationService by lazy {
NotificationService(parentContext, appStore)
}
override val remoteParticipantHandler by lazy {
RemoteParticipantHandler(configuration, appStore, callingSDKWrapper)
}
override val callHistoryRepository by lazy {
CallHistoryRepositoryImpl(applicationContext, logger)
}
private val localOptions by lazy {
configuration.callCompositeLocalOptions
}
//region Redux
// Initial State
private val initialState by lazy {
AppReduxState(
configuration.callConfig?.displayName,
localOptions?.isCameraOn == true,
localOptions?.isMicrophoneOn == true
)
}
// Reducers
private val callStateReducer get() = CallStateReducerImpl()
private val participantStateReducer = ParticipantStateReducerImpl()
private val localParticipantStateReducer get() = LocalParticipantStateReducerImpl()
private val permissionStateReducer get() = PermissionStateReducerImpl()
private val lifecycleReducer get() = LifecycleReducerImpl()
private val errorReducer get() = ErrorReducerImpl()
private val navigationReducer get() = NavigationReducerImpl()
private val audioSessionReducer get() = AudioSessionStateReducerImpl()
// Middleware
private val appMiddleware get() = mutableListOf(callingMiddleware)
private val callingMiddleware: Middleware<ReduxState> by lazy {
CallingMiddlewareImpl(
callingMiddlewareActionHandler,
logger
)
}
private val appReduxStateReducer: Reducer<ReduxState> by lazy {
AppStateReducer(
callStateReducer,
participantStateReducer,
localParticipantStateReducer,
permissionStateReducer,
lifecycleReducer,
errorReducer,
navigationReducer,
audioSessionReducer,
) as Reducer<ReduxState>
}
//endregion
//region System
private val applicationContext get() = parentContext.applicationContext
override val logger: Logger by lazy { DefaultLogger() }
private val callingSDKWrapper: CallingSDK by lazy {
customCallingSDK
?: CallingSDKWrapper(
applicationContext,
callingSDKEventHandler,
configuration.callConfig
)
}
private val callingSDKEventHandler by lazy {
CallingSDKEventHandler(
coroutineContextProvider
)
}
private val callingService by lazy {
CallingService(callingSDKWrapper, coroutineContextProvider)
}
//endregion
//region Threading
private val coroutineContextProvider by lazy {
customCoroutineContextProvider ?: CoroutineContextProvider()
}
private val storeDispatcher by lazy {
customCoroutineContextProvider?.SingleThreaded ?: coroutineContextProvider.SingleThreaded
}
//endregion
}
|
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'business-partner',
data: { pageTitle: 'bisterApp.businessPartner.home.title' },
loadChildren: () => import('./business-partner/business-partner.module').then(m => m.BusinessPartnerModule),
},
{
path: 'organisation',
data: { pageTitle: 'bisterApp.organisation.home.title' },
loadChildren: () => import('./organisation/organisation.module').then(m => m.OrganisationModule),
},
{
path: 'facility',
data: { pageTitle: 'bisterApp.facility.home.title' },
loadChildren: () => import('./facility/facility.module').then(m => m.FacilityModule),
},
{
path: 'customer',
data: { pageTitle: 'bisterApp.customer.home.title' },
loadChildren: () => import('./customer/customer.module').then(m => m.CustomerModule),
},
{
path: 'agent',
data: { pageTitle: 'bisterApp.agent.home.title' },
loadChildren: () => import('./agent/agent.module').then(m => m.AgentModule),
},
{
path: 'project-type',
data: { pageTitle: 'bisterApp.projectType.home.title' },
loadChildren: () => import('./project-type/project-type.module').then(m => m.ProjectTypeModule),
},
{
path: 'project',
data: { pageTitle: 'bisterApp.project.home.title' },
loadChildren: () => import('./project/project.module').then(m => m.ProjectModule),
},
{
path: '',
data: { pageTitle: 'bisterApp.project.home.title' },
loadChildren: () => import('./project/project.module').then(m => m.ProjectModule),
},
{
path: 'project-activity',
data: { pageTitle: 'bisterApp.projectActivity.home.title' },
loadChildren: () => import('./project-activity/project-activity.module').then(m => m.ProjectActivityModule),
},
{
path: 'product-activity',
data: { pageTitle: 'bisterApp.productActivity.home.title' },
loadChildren: () => import('./product-activity/product-activity.module').then(m => m.ProductActivityModule),
},
{
path: 'product',
data: { pageTitle: 'bisterApp.product.home.title' },
loadChildren: () => import('./product/product.module').then(m => m.ProductModule),
},
{
path: 'tag',
data: { pageTitle: 'bisterApp.tag.home.title' },
loadChildren: () => import('./tag/tag.module').then(m => m.TagModule),
},
{
path: 'category',
data: { pageTitle: 'bisterApp.category.home.title' },
loadChildren: () => import('./category/category.module').then(m => m.CategoryModule),
},
{
path: 'product-attribute',
data: { pageTitle: 'bisterApp.productAttribute.home.title' },
loadChildren: () => import('./product-attribute/product-attribute.module').then(m => m.ProductAttributeModule),
},
{
path: 'product-attribute-term',
data: { pageTitle: 'bisterApp.productAttributeTerm.home.title' },
loadChildren: () => import('./product-attribute-term/product-attribute-term.module').then(m => m.ProductAttributeTermModule),
},
{
path: 'product-variation-attribute-term',
data: { pageTitle: 'bisterApp.productVariationAttributeTerm.home.title' },
loadChildren: () =>
import('./product-variation-attribute-term/product-variation-attribute-term.module').then(
m => m.ProductVariationAttributeTermModule
),
},
{
path: 'product-review',
data: { pageTitle: 'bisterApp.productReview.home.title' },
loadChildren: () => import('./product-review/product-review.module').then(m => m.ProductReviewModule),
},
{
path: 'project-review',
data: { pageTitle: 'bisterApp.projectReview.home.title' },
loadChildren: () => import('./project-review/project-review.module').then(m => m.ProjectReviewModule),
},
{
path: 'product-variation',
data: { pageTitle: 'bisterApp.productVariation.home.title' },
loadChildren: () => import('./product-variation/product-variation.module').then(m => m.ProductVariationModule),
},
{
path: 'project-specification-group',
data: { pageTitle: 'bisterApp.projectSpecificationGroup.home.title' },
loadChildren: () =>
import('./project-specification-group/project-specification-group.module').then(m => m.ProjectSpecificationGroupModule),
},
{
path: 'product-specification-group',
data: { pageTitle: 'bisterApp.productSpecificationGroup.home.title' },
loadChildren: () =>
import('./product-specification-group/product-specification-group.module').then(m => m.ProductSpecificationGroupModule),
},
{
path: 'project-specification',
data: { pageTitle: 'bisterApp.projectSpecification.home.title' },
loadChildren: () => import('./project-specification/project-specification.module').then(m => m.ProjectSpecificationModule),
},
{
path: 'product-specification',
data: { pageTitle: 'bisterApp.productSpecification.home.title' },
loadChildren: () => import('./product-specification/product-specification.module').then(m => m.ProductSpecificationModule),
},
{
path: 'attachment',
data: { pageTitle: 'bisterApp.attachment.home.title' },
loadChildren: () => import('./attachment/attachment.module').then(m => m.AttachmentModule),
},
{
path: 'certification',
data: { pageTitle: 'bisterApp.certification.home.title' },
loadChildren: () => import('./certification/certification.module').then(m => m.CertificationModule),
},
{
path: 'promotion',
data: { pageTitle: 'bisterApp.promotion.home.title' },
loadChildren: () => import('./promotion/promotion.module').then(m => m.PromotionModule),
},
{
path: 'payment-schedule',
data: { pageTitle: 'bisterApp.paymentSchedule.home.title' },
loadChildren: () => import('./payment-schedule/payment-schedule.module').then(m => m.PaymentScheduleModule),
},
{
path: 'purchase-order',
data: { pageTitle: 'bisterApp.purchaseOrder.home.title' },
loadChildren: () => import('./purchase-order/purchase-order.module').then(m => m.PurchaseOrderModule),
},
{
path: 'booking-order',
data: { pageTitle: 'bisterApp.bookingOrder.home.title' },
loadChildren: () => import('./booking-order/booking-order.module').then(m => m.BookingOrderModule),
},
{
path: 'address',
data: { pageTitle: 'bisterApp.address.home.title' },
loadChildren: () => import('./address/address.module').then(m => m.AddressModule),
},
{
path: 'phonenumber',
data: { pageTitle: 'bisterApp.phonenumber.home.title' },
loadChildren: () => import('./phonenumber/phonenumber.module').then(m => m.PhonenumberModule),
},
{
path: 'notification',
data: { pageTitle: 'bisterApp.notification.home.title' },
loadChildren: () => import('./notification/notification.module').then(m => m.NotificationModule),
},
{
path: 'enquiry',
data: { pageTitle: 'bisterApp.enquiry.home.title' },
loadChildren: () => import('../enquiry/enquiry.module').then(m => m.EnquiryModule),
},
{
path: 'enquiry-response',
data: { pageTitle: 'bisterApp.enquiryResponse.home.title' },
loadChildren: () => import('./enquiry-response/enquiry-response.module').then(m => m.EnquiryResponseModule),
},
{
path: 'invoice',
data: { pageTitle: 'bisterApp.invoice.home.title' },
loadChildren: () => import('./invoice/invoice.module').then(m => m.InvoiceModule),
},
{
path: 'transaction',
data: { pageTitle: 'bisterApp.transaction.home.title' },
loadChildren: () => import('./transaction/transaction.module').then(m => m.TransactionModule),
},
{
path: 'tax-rate',
data: { pageTitle: 'bisterApp.taxRate.home.title' },
loadChildren: () => import('./tax-rate/tax-rate.module').then(m => m.TaxRateModule),
},
{
path: 'tax-class',
data: { pageTitle: 'bisterApp.taxClass.home.title' },
loadChildren: () => import('./tax-class/tax-class.module').then(m => m.TaxClassModule),
},
{
path: 'refund',
data: { pageTitle: 'bisterApp.refund.home.title' },
loadChildren: () => import('./refund/refund.module').then(m => m.RefundModule),
},
/* jhipster-needle-add-entity-route - JHipster will add entity modules routes here */
]),
],
})
export class EntityRoutingModule {}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Fixed.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ncastell <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/22 17:43:55 by ncastell #+# #+# */
/* Updated: 2024/06/17 17:37:41 by ncastell ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FIXED_HPP
# define FIXED_HPP
#include <iostream>
#include <math.h>
class Fixed
{
private:
int num;
static const int rawBits = 8;
public:
Fixed();
Fixed(const int _num);
Fixed(const float _num);
Fixed(const Fixed& other); // copy constructor
Fixed& operator = (const class Fixed& other); // copy assignment operator
~Fixed();
// getters && setters
int getRawBits(void) const;
void setRawBits(int const raw);
float toFloat(void) const; // const: el objeto no es modificado internamente
int toInt(void) const;
// overloading operator functions
Fixed operator+(const Fixed& other) const;
Fixed operator-(const Fixed& other) const;
Fixed operator*(const Fixed& other) const;
Fixed operator/(const Fixed& other) const;
bool operator>(const Fixed& compared) const;
bool operator<(const Fixed& compared) const;
bool operator>=(const Fixed& compared) const;
bool operator<=(const Fixed& compared) const;
bool operator==(const Fixed& compared) const;
bool operator!=(const Fixed& compared) const;
Fixed& operator++(void);
Fixed operator++(int);
Fixed& operator--(void);
Fixed operator--(int);
static Fixed& max(Fixed& a, Fixed& b);
static Fixed& min(Fixed& a, Fixed& b);
static const Fixed& min(const Fixed& a, const Fixed& b);
static const Fixed& max(const Fixed& a, const Fixed& b);
};
std::ostream& operator<<(std::ostream &out, const Fixed &fixed);
#endif
|
import functions_framework
from datetime import date
from urllib.request import urlopen
import pandas as pd
from zipfile import ZipFile
from io import BytesIO
@functions_framework.http
def extract_dados_anatel_acessos(request):
"""
Objective: Get the latest year csv.
This code is adapted to run on Google Cloud Function
configuration settings: 4 GB Ram to be able to extract the zip file in the memory.
"""
bucket_dst = 'gs://bucket-name'
# Source link
url = "https://www.anatel.gov.br/dadosabertos/paineis_de_dados/acessos/acessos_banda_larga_fixa.zip"
# Returns the current local date
today = date.today()
# Target table within the acessos_banda_larga_fixa.zip file
current_year_data = f"Acessos_Banda_Larga_Fixa_{today.year}.csv"
# Csv final name
csv_name = f"{bucket_dst}/ANATEL_ACESSOS_BANDA_LARGA_FIXA_{today.year}.csv"
# Get http response
zip_request = urlopen(url)
# Get zip file
acessos_banda_larga_fixa_zip = ZipFile(BytesIO(zip_request.read()))
try:
# Read csv file zipped into DataFrame
df_current_year_data = pd.read_csv(acessos_banda_larga_fixa_zip.open(current_year_data), sep=';', encoding='utf-8')
# Write the dataframe to csv file
df_current_year_data.to_csv(csv_name, sep=';', encoding='utf-8', index=False)
except:
# Do the same but with the previous year
current_year_data = f"Acessos_Banda_Larga_Fixa_{today.year - 1}.csv"
csv_name = f"{bucket_dst}/ANATEL_ACESSOS_BANDA_LARGA_FIXA_{today.year - 1}.csv"
df_current_year_data = pd.read_csv(acessos_banda_larga_fixa_zip.open(current_year_data), sep=';', encoding='utf-8')
df_current_year_data.to_csv(csv_name, sep=';', encoding='utf-8', index=False)
return f'arquivo criado: {csv_name}'
|
import { Storage as GoogleCloudStorage, UploadOptions } from '@google-cloud/storage';
import { v4 } from 'uuid';
import { HandleableError } from '@/lib/error';
type StorageConfig = {
storage: GoogleCloudStorage;
bucket: string;
directory: string;
};
let storage?: StorageConfig = undefined;
type CreateStorage = () => StorageConfig;
const createStorage: CreateStorage = () => {
const googleCloudStorage = new GoogleCloudStorage({
projectId: process.env.GOOGLE_CLOUD_PROJECT,
keyFilename: process.env.GOOGLE_CLOUD_KEY,
credentials: { // TODO
client_email,
private_key,
},
});
return {
storage: googleCloudStorage,
bucket: process.env.STORAGE_BUCKET,
directory: process.env.STORAGE_DIRECTORY,
};
}
type UploadFile = (config: StorageConfig) => (localFilePath: string, extension: string) => Promise<string | FileError>;
const uploadFile: UploadFile = ({ storage, bucketName, dir }) => async (localFilePath, extension) => {
try {
const storageFileName = `${v4()}.${extension}`;
const bucket = storage.bucket(bucketName);
await bucket.upload(localFilePath, { destination: `${dir}/${storageFileName}`, gzip: true });
return storageFileName;
} catch (e) {
return new FileError(
'upload',
file_path,
e,
'ファイルアップロードできませんでした'
);
}
}
type GeneratePreSignedUrl = (config: StorageConfig) => (filePath: string) => Promise<string | FileError>
const generatePreSignedUrl: GeneratePreSignedUrl = ({ storage, bucketName, dir }) => (filePath) => {
try {
const bucket = storage.bucket(bucketName);
const [ url ] = await bucket.file(`${dir}/${filePath}`).getSignedUrl({
version: 'v4',
action: 'read',
expires: Date.now() + (15 * 60 * 1000), // 15 minutes
});
return url;
} catch (e) {
return new FileError(
'preSignedUrl',
filePath,
e,
'署名付きURLを発行できませんでした'
);
}
}
export type Storage = {
generatePreSignedUrl: GeneratePreSignedUrl;
uploadFile: UploadFile
}
export type GetStorage = () => Storage;
export const getStorage: GetStorage = () => {
if (storage) {
storage = createStorage();
}
return {
uploadFile: uploadFile(storage),
generatePreSignedUrl: generatePreSignedUrl(storage),
};
};
export class FileError extends HandleableError {
override readonly name = 'lib.fileStorage.FileError' as const;
constructor(
readonly action: string,
readonly path: string,
readonly exception: Error,
readonly message: string,
) {
super();
}
}
|
package org.wit.repository
import org.wit.helpers.users
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.wit.config.DBConfig
import org.wit.db.Users
import org.wit.domain.UserDTO
import org.wit.helpers.ServerContainer
import org.wit.helpers.nonExistingEmail
import org.wit.helpers.populateUserTable
//retrieving some test data from Fixtures
val user1 = users.get(0)
val user2 = users.get(1)
val user3 = users.get(2)
val user4 = users.get(3)
class UserDAOTest {
companion object {
//Make a connection to a local, in memory H2 database or Heroku postgres database.
@BeforeAll
@JvmStatic
//-------TO BE USED WITH INTERNAL DB----internal fun setupInMemoryDatabaseConnection() {
internal fun setupDatabaseConnection() {
val db = DBConfig().getDbConnection()
val origin = "https://health-tracker-20096053.herokuapp.com"
/* TO BE USED WITH INTERNAL APP
val app = ServerContainer.instance
val origin = "http://localhost:" + app.port()
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "root", password = "") */
}
}
internal fun emptyUserTable(){
val userDAO = UserDAO()
userDAO.emptyUserTable()
}
/* internal fun populateUserTable(): UserDAO{
SchemaUtils.create(Users)
val userDAO = UserDAO()
userDAO.delete(user1.userId)
userDAO.deleteByEmail(user1.email)
userDAO.save(user1)
userDAO.delete(user2.userId)
userDAO.deleteByEmail(user2.email)
userDAO.save(user2)
userDAO.delete(user3.userId)
userDAO.deleteByEmail(user3.email)
userDAO.save(user3)
userDAO.delete(user4.userId)
userDAO.deleteByEmail(user4.email)
userDAO.save(user4)
return userDAO
}
*/
@Nested
inner class CreateUsers {
@Test
fun `multiple users added to table can be retrieved successfully`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(4, userDAO.getAll().size)
assertEquals(user1, userDAO.findById(user1.userId))
assertEquals(user2, userDAO.findById(user2.userId))
assertEquals(user3, userDAO.findById(user3.userId))
assertEquals(user4, userDAO.findById(user4.userId))
}
emptyUserTable()
}
}
@Nested
inner class ReadUsers {
@Test
fun `getting all users from a populated table returns all rows`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(4, userDAO.getAll().size)
}
emptyUserTable()
}
@Test
fun `get user by id that doesn't exist, results in no user returned`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(null, userDAO.findById(5))
}
emptyUserTable()
}
@Test
fun `get user by id that exists, results in a correct user returned`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(user4, userDAO.findById(4))
}
emptyUserTable()
}
@Test
fun `get all users over empty table returns none`() {
transaction {
//Arrange - create and setup userDAO object
SchemaUtils.create(Users)
val userDAO = UserDAO()
//Act & Assert
assertEquals(0, userDAO.getAll().size)
}
emptyUserTable()
}
@Test
fun `get user by email that doesn't exist, results in no user returned`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(null, userDAO.findByEmail(nonExistingEmail))
}
emptyUserTable()
}
@Test
fun `get user by email that exists, results in correct user returned`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(user2, userDAO.findByEmail(user2.email))
}
emptyUserTable()
}
}
@Nested
inner class DeleteUsers {
@Test
fun `deleting a non-existant user in table results in no deletion`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(4, userDAO.getAll().size)
userDAO.delete(5)
assertEquals(4, userDAO.getAll().size)
}
emptyUserTable()
}
@Test
fun `deleting an existing user in table results in record being deleted`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(4, userDAO.getAll().size)
userDAO.delete(user4.userId)
assertEquals(3, userDAO.getAll().size)
}
emptyUserTable()
}
@Test
fun `deleting a non-existant user in table using email results in no deletion`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(4, userDAO.getAll().size)
userDAO.deleteByEmail(nonExistingEmail)
assertEquals(4, userDAO.getAll().size)
}
emptyUserTable()
}
@Test
fun `deleting an existing user in table using email results in record being deleted`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
assertEquals(4, userDAO.getAll().size)
userDAO.deleteByEmail(user4.email)
assertEquals(3, userDAO.getAll().size)
}
emptyUserTable()
}
}
@Nested
inner class UpdateUsers {
@Test
fun `updating existing user in table results in successful update`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
val user4Updated = UserDTO(4, "new firstName", "new LastName", "male","[email protected]","1234567890",31, "Hillcrest", 1.71,
80.51,"niju","abc")
userDAO.update(user4.userId, user4Updated)
assertEquals(user4Updated, userDAO.findById(4))
}
emptyUserTable()
}
@Test
fun `updating non-existant user in table results in no updates`() {
transaction {
//Arrange - create and populate table with three users
val userDAO = populateUserTable()
//Act & Assert
val user5Updated = UserDTO(5, "new firstName", "new LastName", "male","[email protected]","1234567890",31,"Hillcrest", 1.71,
80.51,"niju","abc")
userDAO.update(5, user5Updated)
assertEquals(null, userDAO.findById(5))
assertEquals(4, userDAO.getAll().size)
}
emptyUserTable()
}
}
}
|
package dev.cobblesword.ctf.game;
import dev.cobblesword.ctf.CaptureTheFlagPlugin;
import dev.cobblesword.ctf.game.commands.GameCommands;
import dev.cobblesword.ctf.game.team.TeamPrefix;
import dev.cobblesword.ctf.game.team.TeamType;
import dev.cobblesword.ctf.lobby.LobbyModule;
import dev.cobblesword.libraries.common.messages.CC;
import lombok.Getter;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;
public class GameManager implements Runnable
{
@Getter
private Game game;
@Getter
private GameState state = GameState.SETTING_UP;
@Getter
private int secondsRemaining = -1;
@Getter
private List<Player> gamers = new ArrayList<Player>();
public GameManager(JavaPlugin plugin)
{
this.game = new Game(CaptureTheFlagPlugin.getInstance());
CaptureTheFlagPlugin.getInstance().getCommandFramework().registerCommands(new GameCommands());
this.setState(GameState.WAITING_FOR_PLAYERS);
Bukkit.getPluginManager().registerEvents(new GameManagerListener(this), plugin);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this, 20L, 20L);
}
public GameState getState() {
return this.state;
}
public void setState(GameState state)
{
System.out.println(this.state + " => " + state);
this.state = state;
secondsRemaining = state.getSeconds();
}
public void join(Player player)
{
this.gamers.add(player);
if(game != null)
{
this.game.join(player);
}
}
public void leave(Player player)
{
this.gamers.remove(player);
if(game != null)
{
this.game.leave(player);
}
}
public void backToLobby()
{
LobbyModule lobbyModule = CaptureTheFlagPlugin.getInstance().getLobbyModule();
Location spawnLocation = lobbyModule.getSpawnLocation();
for (Player player : Bukkit.getOnlinePlayers())
{
if(player.getVehicle() != null)
{
player.getVehicle().eject();
player.eject();
}
player.setDisplayName(player.getName());
lobbyModule.applyLobbyKit(player);
player.teleport(spawnLocation);
}
}
public void setUpNextGame()
{
this.game = new Game(CaptureTheFlagPlugin.getInstance());
for (Player player : Bukkit.getOnlinePlayers())
{
// Add to next game
this.game.join(player);
}
}
public void handleTabBanner()
{
for (Player onlinePlayer : Bukkit.getOnlinePlayers())
{
BaseComponent header = new TextComponent("Capture The Flag");
header.setBold(true);
header.setColor(ChatColor.GOLD);
header.addExtra("\n");
int tabHeaderSize = 80;
if(state == GameState.WAITING_FOR_PLAYERS)
{
header.addExtra(CC.gray + "Waiting for players" + "\n");
}
else if(state == GameState.COUNTDOWN)
{
header.addExtra(CC.gray + "Starting in " + this.secondsRemaining + " seconds" + "\n");
}
else if(state == GameState.PREPARE_GAME)
{
header.addExtra(CC.gray + "Good Luck!" + "\n");
}
else if(state == GameState.IN_PROGRESS)
{
header.addExtra(CC.gray + this.secondsRemaining + " seconds remaining" + "\n");
}
else if(state == GameState.CELEBRATE)
{
if(this.getGame().getWinningTeam() != null)
{
header.addExtra(CC.gray + this.getGame().getWinningTeam().getChatColor() + "VICTORY" + "\n");
}
else
{
header.addExtra(CC.gray + "DRAW!" + "\n");
}
}
BaseComponent footer = new TextComponent("\nCobbleSword.dev\n");
footer.setBold(true);
footer.setColor(ChatColor.AQUA);
onlinePlayer.setPlayerListHeaderFooter(header, footer);
}
}
@Override
public void run()
{
int minPlayers = 2;
handleTabBanner();
if(state == GameState.WAITING_FOR_PLAYERS)
{
if(gamers.size() >= minPlayers)
{
System.out.println("has enough players");
this.setState(GameState.COUNTDOWN);
}
}
if(state == GameState.COUNTDOWN)
{
if(gamers.size() < minPlayers)
{
Bukkit.broadcastMessage(CC.red + "No enough players to start. Requires " + minPlayers + " players to start!");
this.setState(GameState.WAITING_FOR_PLAYERS);
}
}
if(state == GameState.CELEBRATE)
{
if(game.hasWinner())
{
for (UUID winnerUUID : this.game.getWinningTeam().getPlayers())
{
Player player = Bukkit.getPlayer(winnerUUID);
Firework firework = player.getWorld().spawn(player.getLocation(), Firework.class);
FireworkMeta meta = firework.getFireworkMeta();
meta.addEffect(FireworkEffect.builder()
.withColor(this.game.getWinningTeam().getDyeColor())
.with(FireworkEffect.Type.BALL)
.build());
firework.setFireworkMeta(meta);
}
}
}
if(state == GameState.PREPARE_GAME)
{
this.game.onStart();
this.setState(GameState.IN_PROGRESS);
this.game.setInProgress(true);
List<Player> allPlayers = new ArrayList<>();
List<Player> redPlayers = new ArrayList<>();
List<Player> bluePlayers = new ArrayList<>();
for (UUID playerId : this.getGame().getTeam(TeamType.RED).getPlayers()) {
Player player = Bukkit.getPlayer(playerId);
if(player != null)
{
allPlayers.add(player);
redPlayers.add(player);
}
}
for (UUID playerId : this.getGame().getTeam(TeamType.BLUE).getPlayers()) {
Player player = Bukkit.getPlayer(playerId);
if(player != null)
{
allPlayers.add(player);
bluePlayers.add(player);
}
}
TeamPrefix.createTeamWithPlayer(CC.red, "red_team", redPlayers, allPlayers);
TeamPrefix.createTeamWithPlayer(CC.blue, "blue_team", bluePlayers, allPlayers);
}
boolean changeState = secondsRemaining == 0;
if((game.hasWinner() || changeState) && state == GameState.IN_PROGRESS)
{
this.setState(GameState.CELEBRATE);
if(changeState && !game.hasWinner() )
{
game.onFinish(FinishReason.TIME_OUT);
}
else
{
game.onFinish(FinishReason.FLAG_CAPTURED);
}
}
if(changeState)
{
if(state == GameState.COUNTDOWN)
{
this.setState(GameState.PREPARE_GAME);
}
if(state == GameState.CELEBRATE)
{
this.game.onExit();
TeamPrefix.removeTeamWithPlayer("red_team", Bukkit.getOnlinePlayers());
TeamPrefix.removeTeamWithPlayer("blue_team", Bukkit.getOnlinePlayers());
this.setState(GameState.WAITING_FOR_PLAYERS);
backToLobby();
setUpNextGame();
}
}
if(secondsRemaining != -1)
{
if(this.state == GameState.COUNTDOWN)
{
if(Stream.of(1, 2, 3, 4, 5, 10, 15, 30, 45, 60).anyMatch(sec -> secondsRemaining == sec))
{
Bukkit.broadcastMessage(CC.gray + "Game starting in " + CC.highlight(this.secondsRemaining + "") + " seconds.");
}
if(Stream.of(1, 2, 3, 4, 5, 10).anyMatch(sec -> secondsRemaining == sec))
{
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.NOTE_PLING, 1f, 1f);
}
}
}
if(this.state == GameState.IN_PROGRESS)
{
// minutes
if(Stream.of(60, (60 * 2), (60 * 5), (60 * 10)).anyMatch(sec -> secondsRemaining == sec))
{
Bukkit.broadcastMessage(CC.gray + "Game ends in " + CC.highlight((this.secondsRemaining / 60) + "") + " minutes.");
}
// seconds
if(Stream.of(1, 2, 3, 4, 5, 10, 30, 45).anyMatch(sec -> secondsRemaining == sec))
{
Bukkit.broadcastMessage(CC.gray + "Game ends in " + CC.highlight(this.secondsRemaining + "") + " seconds.");
}
}
secondsRemaining--;
}
}
}
|
//
// PopupView.swift
// HeavyLog
//
// Created by Sebastian Staszczyk on 04/09/2021.
//
import Shared
import SwiftUI
struct PopupView: View {
@ObservedObject var viewModel: PopupVM
var body: some View {
VStack(alignment: .leading, spacing: .spacingHuge) {
Text(viewModel.title).textHeadlineBigBold
VStack(alignment: .leading, spacing: .spacingBig) {
VStack(alignment: .leading, spacing: .spacingSmall) {
if let message = viewModel.message {
Text(message).textBodyNormal
}
if let inputVM = viewModel.textFieldVM {
TextFieldView(viewModel: inputVM)
}
}
if let picker = viewModel.picker {
VStack(alignment: .leading, spacing: .spacingSmall) {
Text(picker.hint).textBodyNormal
IntegerPickerView(viewModel: picker.viewModel, maxHeight: 100)
}
}
}
HStack(spacing: .spacingSmall) {
Button(.common_cancel, action: viewModel.dismissPopup)
.buttonStyle(BaseButtonStyle(.secondary(.medium)))
.displayIf(viewModel.shouldDisplayCancelButton)
Button(.common_ok, action: viewModel.action)
.buttonStyle(BaseButtonStyle(viewModel.isDestructive ? .destructive(.medium) : .action(.medium)))
}
.frame(maxWidth: .infinity)
}
.padding(.spacingBig)
.frame(width: UIScreen.width - 2 * CGFloat.spacingMedium)
.background(Color.backgroundSecondary)
.cornerRadius(.cornerRadiusBase)
.shadow(radius: 10)
}
}
// MARK: - Preview
struct Popup_Previews: PreviewProvider {
static var previews: some View {
Group {
PopupView(viewModel: .init(.sampleInfo, dismiss: {}))
PopupView(viewModel: .init(.sampleAction, dismiss: {}))
PopupView(viewModel: .init(.sampleTextField, dismiss: {}))
PopupView(viewModel: .init(.sampleTextFieldAndPicker, dismiss: {}))
}
.previewSizeThatFits()
}
}
|
<!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>Stack Overflow Clone</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>
<body style="overflow-x:hidden;font-family: 'Roboto Slab', serif;border-top:4px solid #F48024;">
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-sm bg-light" id="navbar_top" style="box-shadow: 0 2px 5px #BBC0C4">
<a class="navbar-brand" href="/">
<img src="https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg" alt="logo" width="400" height="28" class="d-inline-block align-text-top">
</a>
<a class="nav-link" style="position:absolute;right:1100px;" href="/about">About</a>
<form class="d-flex" role="search" style="position:absolute;right:700px;" method="post" action="/search">
<input class="form-control me-2" type="search" name="searchkeyword" placeholder="Search..." aria-label="Search">
<button class="btn btn-outline-primary" type="submit">Search</button>
</form>
<form class="d-flex" role="login" style="position:absolute;right:50px;">
<% if(session.user_id && session.userType=='user'){ %>
<input type="text" style="border:none;color:rgb(10, 112, 246);text-align:center;font-weight:bold" name="username" id="" value="Welcome, User!" readonly>
<a href="/logout" class="btn btn-primary">Logout</a>
<% } else if(session.user_id && session.userType=='admin') { %>
<input type="text" style="border:none;color:rgb(10, 112, 246);text-align:center;font-weight:bold" name="username" id="" value="Welcome, Admin!" readonly>
<a href="/logout" class="btn btn-primary">Logout</a>
<% } else { %>
<button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#loginModal" style="margin-right:10px;">
Login
</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#signupModal">
Sign up
</button>
<% } %>
</form>
</nav>
<!-- Login Modal -->
<div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="position:absolute;right:10px;top:5px;"></button>
<img src="https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg" alt="logo " width="200 " height="160px " style="position:relative;left:150px;top:20px; " class="d-inline-block align-text-top " />
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">User Login </h5>
</div>
<form action="/login" method="post">
<div class="modal-body">
<div class="mb-3 row ">
<div class="dropdown" style="margin:20px 5px;">
<select class="form-select" id="usertype" name="utype" aria-label="ChooseUser">
<option selected>--Choose a User--</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
</div>
<label for="Email " class="col-sm-2 col-form-label ">User ID</label>
<div class="col-sm-10 ">
<input type="email" class="form-control " id="LoginEmail" name="username" placeholder="[email protected]" required>
</div>
</div>
<div class="mb-3 row ">
<label for="inputPassword" class="col-sm-2 col-form-label ">Password</label>
<div class="col-sm-10 ">
<input type="password" name="password" class="form-control " id="inputPassword" required>
</div>
</div>
<div class="mb-3 row">
<a href="/forgetpass">Forget Password</a>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
<button type="Submit" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</div>
</div>
<!-- Signup Modal -->
<div class="modal fade" id="signupModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="position:absolute;right:10px;top:5px;"></button>
<img src="https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg" alt="logo " width="200 " height="160px " style="position:relative;left:150px;top:20px; " class="d-inline-block align-text-top " />
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">User SignUp </h5>
</div>
<form action="/create" method="post">
<div class="modal-body">
<div class="mb-3 row ">
<label for="Email " class="col-sm-2 col-form-label ">Email ID</label>
<div class="col-sm-10 ">
<input type="email" class="form-control" name="EmailID" id="Email" placeholder="[email protected]" required>
</div>
</div>
<div class="mb-3 row ">
<label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10 ">
<input type="password" name="Password" placeholder="password" class="form-control" id="inputPasswordSignup" required>
</div>
</div>
<!-- Confirm Password Added -->
<div class="mb-3 row ">
<label for="inputPassword" class="col-sm-2 col-form-label">Confirm Password</label>
<div class="col-sm-10 ">
<input type="password" name="CPassword" placeholder="confirm password" class="form-control" id="inputConfirmPassword" required onkeyup="validate_password()">
</div>
</div>
</div>
<span id="wrong_pass_alert"></span>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
<button type="Submit" id="create" class="btn btn-primary" data-toggle="modal" data-target="#loginModal">Register</button>
</div>
</form>
</div>
</div>
</div>
<!-- Offcanvas Side navbar -->
<div class="container ">
<button class="btn btn-primary d-lg-none" style="margin-top:15px;margin-left:10px " type="button " data-bs-toggle="offcanvas " data-bs-target="#offcanvasResponsive " aria-controls="offcanvasResponsive "><i class="material-icons " style="font-size:48px;color:white ">menu</i></button>
<div class="offcanvas-lg offcanvas-start" tabindex="-1" id="offcanvasResponsive " aria-labelledby="offcanvasResponsiveLabel ">
<div class="offcanvas-header ">
<h5 class="offcanvas-title " id="offcanvasResponsiveLabel ">Responsive offcanvas</h5>
<button type="button " class="btn-close " data-bs-dismiss="offcanvas " data-bs-target="#offcanvasResponsive " aria-label="Close "></button>
</div>
<div class="offcanvas-body " style="padding-top:15px; ">
<p class="mb-0 ">
<ul style="list-style-type:none;line-height:40px; ">
<li style="border-right:5px solid #F48024;background-color:aliceblue;padding-right:120px;padding-left:37px;"><a style="text-decoration:none;color:black; " href="/">Questions</a></li>
<li style="padding-right:119px;padding-left:37px;"><a style="text-decoration:none;color:black; " href="/tags">Tags</a></li>
<li style="padding-right:119px;padding-left:37px;"><a style="text-decoration:none;color:black; " href="/viewchart">Dashboard</a></li>
<% if(session.user_id && session.userType=='admin') { %>
<li style="padding-right:119px;padding-left:37px;"><a style="text-decoration:none;color:black; " href="/viewusers">Users</a></li>
<% } %>
</ul>
</p>
</div>
</div>
<!-- Main Content : All Questions -->
<div class="container main-content " style="position:absolute;top:80px;left:380px;border-left:2px solid rgb(195, 184, 184);height:auto; ">
<div class="row justify-content-between ">
<div class="col-4 ">
<h1>All Questions</h1>
</div>
<% if(session.user_id){ %>
<div class="col-4 ">
<a href="/quesans" class="btn btn-primary" name="postquestion" style="border-radius:3px">Post a Question</a>
</div>
<% } %>
</div>
<ul style="list-style-type:none;">
<% if (data.length){
for(var i=0; i < data.length; i++){ %>
<hr width="80%">
<input type="text" name="questid" value="<%= data[i].QuestionID %>" hidden>
<h4>
<!-- Redirect to respective answer -->
<a href="/myans/<%= data[i].QuestionID %>" style="text-decoration:none; color:black;">
<%= data[i].Qsubject %>
</a>
</h4>
<div style="color:#BBC0C4;position:relative;left:900px;top:-40px">
<h6> Asked on:<br>
<%= data[i].DatePosted %>
</h6>
</div>
<li>
<%= data[i].Description %>
</li>
<% if(data[i].Image != null){ %>
<li>
<br>
<img alt="No Question Picture Added" src="http://localhost:3000/images/uploaded_image/<%= data[i].Image%>" height="250" width="250" class="img-circle img-responsive zoomE" style="cursor:zoom-in;">
</li>
<% } %>
<% if(session.user_id){ %>
<div class="col-4 ">
<a href="/postans/<%= data[i].QuestionID %>" class="btn btn-light" name="ansques" style="border-radius:3px;position:relative;left:900px;">Answer</a>
</div>
<% }
}
} %>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js " integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2 " crossorigin="anonymous "></script>
<script>
window.onload = () => {
// (A) GET ALL IMAGES
let all = document.getElementsByClassName("zoomE");
// (B) CLICK TO GO FULLSCREEN
if (all.length > 0) {
for (let i of all) {
i.onclick = () => {
// (B1) EXIT FULLSCREEN
if (document.fullscreenElement != null || document.webkitFullscreenElement != null) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else {
document.webkitCancelFullScreen();
}
}
// (B2) ENTER FULLSCREEN
else {
if (i.requestFullscreen) {
i.requestFullscreen();
} else {
i.webkitRequestFullScreen();
}
}
};
}
}
};
function validate_password() {
var pass = document.getElementById('inputPasswordSignup').value;
var confirm_pass = document.getElementById('inputConfirmPassword').value;
if (pass != confirm_pass) {
document.getElementById('wrong_pass_alert').style.color = 'red';
document.getElementById('wrong_pass_alert').innerHTML = '☒ Use same password.Please enter same passwords.';
document.getElementById('create').disabled = true;
document.getElementById('create').style.opacity = (0.4);
} else {
document.getElementById('wrong_pass_alert').style.color = 'green';
document.getElementById('wrong_pass_alert').innerHTML = '🗹 Password Matched';
document.getElementById('create').disabled = false;
document.getElementById('create').style.opacity = (1);
}
}
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
window.addEventListener('scroll', function() {
if (window.scrollY > 50) {
document.getElementById('navbar_top').classList.add('fixed-top');
// add padding top to show content behind navbar
navbar_height = document.querySelector('.navbar').offsetHeight;
document.body.style.paddingTop = navbar_height + 'px';
} else {
document.getElementById('navbar_top').classList.remove('fixed-top');
// remove padding top from body
document.body.style.paddingTop = '0';
}
});
});
</script>
</body>
</html>
|
#include "main.h"
/**
* _atoi - converts a string to an integer
* @s: the string that is being converted
*
* Return: returns the integer
*/
int _atoi(char *s)
{
unsigned int result;
int sign;
result = 0;
sign = 1;
do {
if (*s == '-')
{
sign *= -1;
}
else if (*s >= '0' && *s <= '9')
{
result = (result * 10) + (*s - '0');
}
else if (result > 0)
break;
} while (*s++);
return (sign * result);
}
|
<script lang="ts">
import Image from "./assets/images/image-header-desktop.jpg";
interface dataI {
id: number;
count: string;
type: string;
}
const data: dataI[] = [
{ id: 1, count: "10k+", type: "companies" },
{ id: 2, count: "314", type: "templates" },
{ id: 3, count: "12M+", type: "queries" },
];
</script>
<main class="min-h-screen flex justify-center items-center p-5 bg-[#090b1a]">
<div class="grid grid-cols-1 max-w-[400px] md:grid-cols-2 bg-[#1b1938] rounded-2xl overflow-hidden md:max-w-[1200px]">
<div class="p-8 md:p-12 lg:p-[4rem] flex flex-col justify-between">
<div class="md:text-left text-center">
<h1 class="text-3xl lg:text-4xl max-w-[400px]">
Get <span>insights</span> that help your business grow.
</h1>
<p class="max-w-[380px] text-[15px] mt-6 ">
Discover the benefits of data analytics and make better decisions
regarding revenue, customer experience, and overall efficiency.
</p>
</div>
<div class="flex text-center md:text-left flex-col md:flex-row max-w-[350px] justify-between mt-4">
{#each data as item (item.id)}
<div class="my-4 md:my-0">
<h5 class="text-2xl">{item.count}</h5>
<h6 class="text-sm">{item.type}</h6>
</div>
{/each}
</div>
</div>
<div class="bg-[#aa5cdb] row-[1] md:col-[2]">
<img src={Image} class="w-full h-full" alt="" />
</div>
</div>
</main>
|
import org.apache.spark.{SparkConf, SparkContext}
object MaxSalary {
System.setProperty("hadoop.home.dir", "C:\\Users\\xx\\Downloads\\Hadoop\\")
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("Emp Dept Assignment").setMaster("local[*]")
val sc = new SparkContext(conf)
// Load the source data file into RDD
val emp_data = sc.textFile("C:\\Users\\xx\\Downloads\\emp_data.txt")
println(emp_data.foreach(println))
// Find first record of the file
val emp_header = emp_data.first()
println(emp_header)
// Remove header from RDD
val emp_data_without_header = emp_data.filter(line => !line.equals(emp_header))
println(emp_data_without_header.foreach(println))
// Get no. of partition of an RDD
println("No. of partition = " + emp_data_without_header.partitions.size)
val emp_salary_list = emp_data_without_header.map{x => x.split(',')}.map{x => (x(5).toDouble)}
println("Highest salaty:"+ emp_salary_list.max())
val max_salary = emp_salary_list.distinct.sortBy(x => x.toDouble, false, 1)
print(max_salary.take(1).foreach(println))
val min_salary = emp_salary_list.distinct.sortBy(x => x.toDouble, true, 1)
print(min_salary.take(1).foreach(println))
val second_highest_salary = max_salary.zipWithIndex().filter(index => index._2 == 1).map(_._1)
print(second_highest_salary.foreach(println))
val second_min_salary = min_salary.zipWithIndex().filter(index => index._2 == 1).map(_._1)
print(second_min_salary.foreach(println))
val salaryWithEmployeeName = emp_data_without_header.map{x => x.split(',')}.map{x => (x(5).toDouble, x(1))}
val maxSalaryEmployee = salaryWithEmployeeName.groupByKey.takeOrdered(1)(Ordering[Double].reverse.on(_._1))
print(maxSalaryEmployee.foreach(println))
emp_data.saveAsTextFile("C:\\Users\\xx\\Downloads\\SparkTest18")
}
}
|
package com.yiruo.common.core.domain.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.yiruo.common.core.domain.entity.SysUser;
import io.jsonwebtoken.lang.Assert;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.*;
/**
* 登录用户身份权限
*
* @author yiruo
*/
public class LoginUser implements UserDetails
{
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
private Long userId;
/**
* 部门ID
*/
private Long deptId;
/**
* 用户唯一标识
*/
private String token;
/**
* 登录时间
*/
private Long loginTime;
/**
* 过期时间
*/
private Long expireTime;
/**
* 登录IP地址
*/
private String ipaddr;
/**
* 登录地点
*/
private String loginLocation;
/**
* 浏览器类型
*/
private String browser;
/**
* 操作系统
*/
private String os;
/**
* 权限列表
*/
private Set<String> permissions;
/**
* 用户信息
*/
private SysUser user;
public Long getUserId()
{
return userId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getDeptId()
{
return deptId;
}
public void setDeptId(Long deptId)
{
this.deptId = deptId;
}
public String getToken()
{
return token;
}
public void setToken(String token)
{
this.token = token;
}
public LoginUser()
{
}
public LoginUser(SysUser user, Set<String> permissions)
{
this.user = user;
this.permissions = permissions;
}
public LoginUser(Long userId, Long deptId, SysUser user, Set<String> permissions)
{
this.userId = userId;
this.deptId = deptId;
this.user = user;
this.permissions = permissions;
}
@JSONField(serialize = false)
@Override
public String getPassword()
{
return user.getPassword();
}
@Override
public String getUsername()
{
return user.getUserName();
}
/**
* 账户是否未过期,过期无法验证
*/
@JSONField(serialize = false)
@Override
public boolean isAccountNonExpired()
{
return true;
}
/**
* 指定用户是否解锁,锁定的用户无法进行身份验证
*
* @return
*/
@JSONField(serialize = false)
@Override
public boolean isAccountNonLocked()
{
return true;
}
/**
* 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
*
* @return
*/
@JSONField(serialize = false)
@Override
public boolean isCredentialsNonExpired()
{
return true;
}
/**
* 是否可用 ,禁用的用户不能身份验证
*
* @return
*/
@JSONField(serialize = false)
@Override
public boolean isEnabled()
{
return true;
}
public Long getLoginTime()
{
return loginTime;
}
public void setLoginTime(Long loginTime)
{
this.loginTime = loginTime;
}
public String getIpaddr()
{
return ipaddr;
}
public void setIpaddr(String ipaddr)
{
this.ipaddr = ipaddr;
}
public String getLoginLocation()
{
return loginLocation;
}
public void setLoginLocation(String loginLocation)
{
this.loginLocation = loginLocation;
}
public String getBrowser()
{
return browser;
}
public void setBrowser(String browser)
{
this.browser = browser;
}
public String getOs()
{
return os;
}
public void setOs(String os)
{
this.os = os;
}
public Long getExpireTime()
{
return expireTime;
}
public void setExpireTime(Long expireTime)
{
this.expireTime = expireTime;
}
public Set<String> getPermissions()
{
return permissions;
}
public void setPermissions(Set<String> permissions)
{
this.permissions = permissions;
}
public SysUser getUser()
{
return user;
}
public void setUser(SysUser user)
{
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
{
return null;
// return Collections.unmodifiableSet(sortAuth());
}
// private static SortedSet<GrantedAuthority> sortAuth(){
// SortedSet<GrantedAuthority> sortedSet=new TreeSet<>(new LoginUser.AuthorityComparator());
// List<GrantedAuthority> lg=AuthorityUtils.createAuthorityList("admin","common");
// for(GrantedAuthority g:lg){
// Assert.notNull(g,"--");
// sortedSet.add(g);
// }
// return sortedSet;
// }
//
// private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
// private static final long serialVersionUID = 560L;
//
// private AuthorityComparator() {
// }
//
// public int compare(GrantedAuthority g1, GrantedAuthority g2) {
// if (g2.getAuthority() == null) {
// return -1;
// } else {
// return g1.getAuthority() == null ? 1 : g1.getAuthority().compareTo(g2.getAuthority());
// }
// }
// }
}
|
<template>
<div class="container">
<div class="navbar">
<span class="logo">REDDDIT</span>
<div class="nav-items">
<span class="nav-item">
<router-link to="/1" class="nav-link">
<font color="black">Main</font>
</router-link>
</span>
|
<span class="nav-item">
<router-link to="/new_question" class="nav-link">
<font color="black">New question</font>
</router-link>
</span>
|
<span class="nav-item">
<router-link to="/my_questions" class="nav-link">
<font color="black">My questions</font>
</router-link>
</span>
|
<span class="nav-item" v-on:click="logout">
<a href="#" class="nav-link">
<font color="black">Logout</font>
</a>
</span>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
async logout() {
try {
await this.$store.dispatch("logout");
this.$router.push("/login");
} catch (error) {
throw new Error(error);
}
}
}
};
</script>
<style lang="css" scoped>
.container {
position: relative;
height: 5vh;
border-bottom: 1px solid grey;
padding: 1rem 2rem;
background-color: #f6f6f6;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
.navbar {
height: 100%;
margin: auto;
display: flex;
align-items: center;
justify-content: space-between;
}
.nav-item:hover {
text-decoration: underline;
}
.nav-link {
text-decoration: none;
}
/* #container {
display: block;
width: 100%;
height: 40px;
padding-top: 20px;
}
.logo {
float: left;
}
.nav-item {
float: right;
}
.nav-item:not(last-child) {
margin-left: 10%;
}
.nav-link {
text-decoration: none;
} */
</style>
|
<h3>Object-Oriented Data Structure Using Java, 4th Edition</h3>
<h4>Student: Patricia Antlitz - NECC Fall 2022 <br> Computer Science II</h4>
<h5>Chapter 4 - Exercise 12</h5>
####variables used:
```java
protected final int DEFCAP = 100; // default capacity
protected T[] elements; // array that holds queue elements
protected int numElements = 0; // number of elements in this queue
protected int front = 0; // index of front of queue
protected int rear; // index of rear of queue
```
###Methods added to `ArrayBoundedQueue.java` as required:
a. `String toString()` creates and returns a string that correctly represents
the current queue. Such a method could prove useful for testing and debugging
the class and for testing and debugging applications that use the class. Assume
each stacked element already provided its own reasonable `toString` method.<br>
```java
public String toString(); //will loop the array, turn it to a string and print it
```
b. `int space()` returns an integer indicating how many empty spaces remain in
the queue.
```java
public int space(); //will print the array size
```
c. `void remove(int count)` removes the front count elements from the
queue, and throws `QueueUnderflowException` if there are less than count
elements in the queue.
```java
public void remove(int count); //user can select how many elements to pop
```
d. `boolean swapStart()` if there are less than two elements on the stack returns
false; otherwise it reverses the order of the top two elements on the
stack and returns true.
```java
public boolean swapStart() //To swap the top 2 elements
```
e. `boolean swapEnd()` if there are less than two elements on the stack returns
false; otherwise it reverses the order of the top two elements on the
stack and returns true.
```java
public boolean swapEnd() //To swap the top 2 elements
```
###Main class: Chapter4_12_PatriciaAntlitz.java
<hr>
<h5>Problems:</h5>
I wanted to use recursion on all methods, but I couldn't find my way around it.
I also had trouble inserting the numbers into the queue. I wanted to do it through a method in ArrayBoundedQueue (a new method)
but method enqueue has a parameter T, which didn't allow me to pass i (int) as a parameter.
I also wanted to add 10 random numbers instead of 0-9. I will, in the future, look for a different approach to random numbers. I couldn't make math.random work.
source:<br>
https://www.softwaretestinghelp.com/java-queue-interface/
https://www.javatpoint.com/java-queue
<hr>
<h5>Technologies</hr>
- JAVA 15.0.1
<hr>
<h3>To run:</h3>
<hr>
IDE:<br>
Build the project and run the Chapter4_12_PatriciaAntlitz.java file
CLI:<br>
* Navigate to the correct directory ....../Chapter4_12_PatriciaAntlitz/src <br>
* Run on terminal:
* javac Chapter4_12_PatriciaAntlitz.java => compile
* java Chapter4_12_PatriciaAntlitz.java => run
by [Patricia Antlitz - GitHub](https://github.com/patybn3)
|
import { View, Text, TouchableOpacity } from "react-native";
import React, { useContext, useState, useEffect } from "react";
import { Button, RadioButton } from "react-native-paper";
import { CartContext } from "@/providers/CartProvider";
import { router } from "expo-router";
const OrderType = () => {
const [showError, setShowError] = useState(false);
const [showDeliveryError, setShowDeliveryError] = useState(false);
const { cartState, cartDispatch } = useContext(CartContext);
const [selectedOrderType, setSelectedOrderType] = useState(
cartState.orderDetail.order_type || ""
);
useEffect(() => {
if (selectedOrderType === "delivery" && checkPrescriptionItems()) {
setSelectedOrderType("");
setShowDeliveryError(true);
} else {
setShowDeliveryError(false);
}
}, [selectedOrderType]);
const checkPrescriptionItems = () => {
return cartState.items.some((item) => item.isPrescriptionRequired);
//return true;
};
const handleContinue = () => {
// update the cart state with the selected order type
cartDispatch({
type: "UPDATE_ORDER_DETAIL",
payload: {
...cartState.orderDetail,
order_type: selectedOrderType,
},
});
// navigate to the next screen
router.push("checkout");
};
return (
<View className="px-8 py-8 space-y-4 h-full">
<Text className="text-center font-psemibold mb-4 text-lg ">
Choose Order Type
</Text>
<View className="w-full items-center flex-row p-2 border border-gray-400 rounded-lg">
<View className="flex-1">
<Text className="text-gray-900 font-pmedium">Delivery</Text>
</View>
{/* radio */}
<RadioButton
value="Delivery"
status={selectedOrderType === "delivery" ? "checked" : "unchecked"}
onPress={() => setSelectedOrderType("delivery")}
disabled={checkPrescriptionItems()}
/>
</View>
<View className="w-full items-center flex-row p-2 border border-gray-400 rounded-lg">
<View className="flex-1">
<Text className="text-gray-900 font-pmedium">Pickup</Text>
</View>
{/* radio */}
<RadioButton
value="Pickup"
status={selectedOrderType === "pickup" ? "checked" : "unchecked"}
onPress={() => setSelectedOrderType("pickup")}
/>
</View>
{showError && (
<Text style={{ color: "red" }}>Please select an order type.</Text>
)}
{checkPrescriptionItems() && (
<Text style={{ color: "red" }}>
Delivery is not available for items that require a prescription.
</Text>
)}
{selectedOrderType == "delivery" && !showDeliveryError && (
<Text className="text-gray-700 ">
You will be paying the delivery fee in cash.
</Text>
)}
<View>
<Button
mode="contained"
onPress={() => {
if (selectedOrderType) {
setShowError(false);
handleContinue();
} else {
setShowError(true);
}
}}
>
Continue
</Button>
</View>
</View>
);
};
export default OrderType;
|
import LoadingSpinner from "~/components/Common/LoadingSpinner";
import { CheckIcon, PencilIcon, XMarkIcon } from "@heroicons/react/24/solid";
import { useRouter } from "next/router";
import { api } from "~/utils/api";
import { toast } from "react-hot-toast";
import { type KeyboardEvent, useState } from "react";
type Props = {
entry: { id: string; title: string };
instructionId: string;
projectId: string;
index: number;
isEditingProject: boolean;
};
export default function TableOfContentBlock({
entry,
instructionId,
projectId,
index,
isEditingProject,
}: Props) {
const [isEditingTitle, setIsEditingTitle] = useState(false);
const [title, setTitle] = useState(entry.title);
const router = useRouter();
const { mutate: deleteInstruction, isLoading: isDeletingInstruction } =
api.instructions.delete.useMutation({
onSuccess: () => {
void router.replace(router.asPath);
},
onError: (e) => {
const errorMessage = e.data?.zodError?.fieldErrors.content;
if (errorMessage && errorMessage[0]) {
toast.error(errorMessage[0]);
} else {
toast.error(
"Failed to create a new instruction. Please try again later."
);
}
},
});
const { mutate: updateInstruction, isLoading: isUpdatingInstruction } =
api.instructions.update.useMutation({
onSuccess: () => {
void router.replace(router.asPath);
setIsEditingTitle(false);
},
});
function handleEnterKeyPress<T = Element>(f: () => void) {
return handleKeyPress<T>(f, "Enter");
}
function handleKeyPress<T = Element>(f: () => void, key: string) {
return (e: KeyboardEvent<T>) => {
if (e.key === key) {
f();
}
};
}
return (
<button
key={entry.id}
className={`flex items-center justify-between border p-4 text-left text-lg font-bold hover:bg-gray-100 ${
instructionId === entry.id ? "bg-gray-300" : ""
}`}
onClick={() => {
void (async () => {
await router.push(
`/projectsv2/${projectId}?instructionId=${entry.id}`
);
})();
}}
>
{isEditingTitle ? (
<div className={"flex items-center"}>
<div className="mt-2">
<input
type="email"
name="email"
id="email"
className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
value={title}
onChange={(e) => setTitle(e.target.value)}
onKeyDown={handleEnterKeyPress(() =>
updateInstruction({
instructionId,
title,
})
)}
/>
</div>
</div>
) : (
<p>
{index + 1}. {entry.title}{" "}
</p>
)}
{(isDeletingInstruction || isUpdatingInstruction) && (
<LoadingSpinner styleOverride={"h-6 w-6"} />
)}
{isEditingTitle && !isUpdatingInstruction && (
<CheckIcon className={"h-6 w-6 text-green-500"} />
)}
{isEditingProject && !isEditingTitle && !isDeletingInstruction && (
<div className={"flex gap-4"}>
<PencilIcon
className={"h-6 w-6 text-indigo-500 hover:cursor-pointer"}
onClick={() => setIsEditingTitle(true)}
/>
<XMarkIcon
className={"h-6 w-6 text-red-500 hover:cursor-pointer"}
onClick={() =>
deleteInstruction({
id: entry.id,
})
}
/>
</div>
)}
</button>
);
}
|
import React, { createContext, useContext, useState } from 'react';
export const StateContext = createContext();
const baseUrl = 'https://google-search3.p.rapidapi.com/api/v1';
export const StateContextProvider = ({ children }) => {
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);
const [searchTerm, setSearchTerm] = useState('elon musk');
const getResults = async (url) => {
setLoading(true);
const res = await fetch(`${baseUrl}${url}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'google-search3.p.rapidapi.com',
'x-rapidapi-key': process.env.REACT_APP_API_KEY,
},
});
const data = await res.json();
if (url.includes("/news")) {
setResults(data?.entries);
}
else{
setResults(data);
}
setLoading(false);
};
return (
<StateContext.Provider value={{ getResults, results, searchTerm, setSearchTerm, loading }}>
{children}
</StateContext.Provider>
);
};
export const useStateContext = () => useContext(StateContext);
|
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:proyecto_peluqueria_fjjm/providers/providers.dart';
import 'package:proyecto_peluqueria_fjjm/screens/screens.dart';
import 'package:provider/provider.dart';
import 'package:proyecto_peluqueria_fjjm/themes/app_themes.dart';
class LoginScreen extends StatelessWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: Builder(builder: (BuildContext context) {
return IconButton(
icon: const Icon(Icons.arrow_circle_left),
color: Colors.blueGrey,
onPressed: () {
final route =
MaterialPageRoute(builder: (context) => const HomeScreen());
Navigator.push(context, route);
},
);
}),
backgroundColor: Colors.white,
),
body: SingleChildScrollView(
child: Column(children: [
ChangeNotifierProvider(
create: (_) => LoginFormProvider(), child: _LoginForm())
]),
),
);
}
}
class _LoginForm extends StatelessWidget {
const _LoginForm({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final loginForm = Provider.of<LoginFormProvider>(context);
return Form(
key: loginForm.formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column(
children: [
const SizedBox(
height: 50,
),
ClipRRect(
borderRadius: BorderRadius.circular(1500),
child: Image.asset(
'assets/splash.jpg',
fit: BoxFit.cover,
width: 150,
),
),
const SizedBox(
height: 30,
),
TextFormField(
autocorrect: false,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: 'ejemplo@ejemplo',
labelText: 'Email',
),
onChanged: (value) => loginForm.email = value,
validator: (value) {
String pattern =
r'^(([^<>()[\]\\.,;:\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,}))$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value ?? '')
? null
: 'El email no es válido';
},
),
const SizedBox(
height: 30,
),
TextFormField(
autocorrect: false,
obscureText: true,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: '*****',
labelText: 'Contraseña',
),
onChanged: (value) => loginForm.password = value,
validator: (value) {
if (value!.isEmpty) {
return 'La contraseña no es válida';
} else if (value.length < 4) {
return 'La longitud mínima es de 4 caracteres';
}
},
),
const SizedBox(
height: 30,
),
MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
disabledColor: Colors.grey,
elevation: 0,
color: AppThemes.primary,
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 80, vertical: 15),
child: Text(
loginForm.isLoading ? 'Espere' : 'Iniciar Sesión',
style: TextStyle(color: Colors.white),
)),
onPressed: loginForm.isLoading
? null
: () async {
FocusScope.of(context).unfocus();
if (!loginForm.isValidForm()) {
alertaCoincidencia(context);
} else {
loginForm.isLoading = true;
await Future.delayed(Duration(seconds: 2));
loginForm.isLoading = false;
final route = MaterialPageRoute(
builder: (context) =>
const AppointmentScreen());
Navigator.pushReplacement(context, route);
}
}),
const SizedBox(
height: 20,
),
TextButton(
onPressed: () {
final route = MaterialPageRoute(
builder: (context) => const ResetPasswordScreen());
Navigator.push(context, route);
},
child: Container(
alignment: AlignmentDirectional.center,
padding: const EdgeInsets.only(right: 10),
child: const Text(
'¿Has olvidado la contraseña?',
style: TextStyle(decoration: TextDecoration.underline),
)),
),
],
)),
);
}
}
void alertaCoincidencia(BuildContext context) {
showDialog(
barrierDismissible: false, // Nos permite pulsar fuera de la alerta
context: context,
builder: ((context) {
return AlertDialog(
title: const Text('¡Atención!'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.circular(20)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text('El email o la contraseña son incorrectos'),
SizedBox(
height: 20,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'))
],
);
}));
}
|
# String,StringBuilder,StringBuffer,Textblock
> 문자열을 다루는 클래스는 다수
* Buffer 유무와 다중 Thread 고려 유무 등으로 쓰임이 달라진다
<hr>
<br>
## 문자열 관련 클래스
#### 각자의 특성에 맞는 사용법이 중요
<br>
### [String 클래스]
```java
String str1 = new String("abc");
String str2 = "abc";
```
* ```new String("abc")``` : 힙 메모리에 인스턴스로 생성되서 해당 인스턴스의 주소를 참조하는 경우
* ```"abc"``` : 상수 풀 (Constant Pool)에 있는 주소를 참조하는 경우
<br>
### [String 클래스 크기 비교]
```java
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1 == str2); // false (인스턴스 별로 다른 주소 값)
String str3 = "abc";
String str4 = "abc";
System.out.println(str3 == str4); // true (같은 문자열은 같은 상수 풀 주소)
```
<br>
### [String 클래스 - Immutable]
```java
private final byte[] value; // new String("<문자열 내용>"); final로 선언이 되어있다 --> Immutable
String java = new String("java");
String android = new String("android");
System.out.println(System.identityHashCode(java)); // 주소값이 다름
java = java.concat(android);
System.out.println(System.identityHashCode(java)); // 주소값이 다름, Garbage Collector의 역할이 커진다
```
* String 클래스에 `+` 연산을 하면 내부적으로 `new StringBuffer().append().append().toString()` 형태가 일어나는데, Java에서는 `new` 연산이 많아질수록 성능에 영향을 주기 때문에, 변화가 많은 상황에서 불변성을 가진 String 클래스를 사용하는 것은 적합하지 않다
<br>
### [StringBuilder, StringBuffer - Mutable]
```java
String java = new String("java");
String android = new String("android");
StringBuilder buffer = new StringBuilder(java);
System.out.println(System.identityHashCode(buffer)); // 같은 인스턴스이기 때문에, 주소값이 같다
buffer.append(android);
System.out.println(System.identityHashCode(java)); // 같은 인스턴스이기 때문에, 주소값이 같다
String test = buffer.toString();
System.out.println(test);
```
* 두 클래스 공통
* 내부적으로 가변적인 버퍼가 있어서, 문자열이 변하더라도, 새로운 인스턴스를 생성하는 것이 아니라, 기존 인스턴스의 내부 버퍼를 줄였다 늘렸다하면서 문자열을 처리한다
* 단일 스레드 : StringBuilder 사용
* 멀티 스레드 : StringBuffer 사용
* 동기화 (Synchronization)을 보장
<br>
### [text block - java13부터]
```java
String strBlock = """
Hello,
hi,
how are you""";
System.out.println(strBlock);
```
<br>
<hr>
<br>
## String 클래스의 단점을 보안해주는 StringBuilder, StringBuffer 유용 기능
#### String 클래스의 불변성으로 비롯되는 에러사항들을 해소
<br>
### [메소드 체이닝]
```java
String str1 = new StringBuilder().append("Hello ").append("World 1").toString();
String str2 = new StringBuffer().append("Hello ").append("World 2").toString();
```
* StringBuilder 및 StringBuffer 클래스는 자기 자신 (this)를 반환하기 때문에, 메소드를 덧붙이면서 기능 구현 가능
|
import { AccountInfo } from '@airgap/beacon-sdk';
import React from 'react';
import Constants from 'src/constants';
import Logger from '../services/logger';
import WalletService from '../services/wallet';
import WalletContext from './WalletContext';
const WalletProvider: React.FC<{ children: React.ReactNode }> = (props) => {
const [connecting, setConnecting] = React.useState(true);
const [account, setAccount] = React.useState<AccountInfo>();
React.useEffect(() => {
WalletService.Tezos.getActiveAccount()
.then((account) => {
setAccount(account);
})
.finally(() => setConnecting(false));
}, []);
const connectTezosWallet = React.useCallback(async () => {
try {
setConnecting(true);
await WalletService.Tezos.connect({
name: Constants.network,
rpc: Constants.rpc,
});
const account = await WalletService.Tezos.getActiveAccount();
setAccount(account);
} catch (e) {
Logger.error(e);
} finally {
setConnecting(false);
}
}, []);
return (
<WalletContext.Provider
value={{
connecting,
pkh: account?.address,
publicKey: account?.publicKey,
connectTezosWallet,
}}
>
{props.children}
</WalletContext.Provider>
);
};
export default WalletProvider;
|
import logging
from amazoncaptcha import AmazonCaptcha
from playwright.sync_api import ElementHandle, Page
def is_captcha_present(page: Page) -> bool:
logging.info("checking if captcha is present...")
return (
page.query_selector("form[action='/errors/validateCaptcha']")
is not None
)
def solve_captcha_with_solver(page: Page) -> str:
logging.info("solving captcha with solver...")
logging.info("finding captcha image ElementHandle...")
# 1. find captcha image ElementHandle
captcha_image: ElementHandle = page.wait_for_selector(
"form[action='/errors/validateCaptcha'] img[src*='Captcha']",
)
# 2. get captcha image src
logging.info("getting captcha image src...")
captcha_image_src: str = captcha_image.get_attribute("src")
# 3. create captcha solver
logging.info("creating captcha solver...")
solver: AmazonCaptcha = AmazonCaptcha.fromlink(captcha_image_src)
# 4. solve captcha
logging.info("solving captcha...")
solved_answer: str = solver.solve()
# 5. type captcha answer to input
logging.info("typing captcha answer to input...")
logging.info(f"captcha answer: {solved_answer}")
page.type("#captchacharacters", solved_answer)
# 6. submit captcha
logging.info("submitting captcha...")
page.click("form[action='/errors/validateCaptcha'] button[type='submit']")
return solved_answer
|
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const { userSignUpInputValidation } = require("../middleware/userSignUpInputValidation");
const { userRedundancyCheck } = require("../middleware/userRedundancyCheck");
const { userAuth } = require("../middleware/userAuth");
const { User } = require("../db");
const { validUserCheck } = require("../middleware/validUserCheck");
const zod = require("zod");
const { setRandomBalance } = require("../middleware/setRandomBalance");
const { checkLoggedIn } = require("../middleware/checkUserLoggedIn");
router.post("/signup",userSignUpInputValidation, userRedundancyCheck,async (req, res)=>{
//Add user to the DB in User collection
try{
const username = req.body.username;
const password = req.body.password;
const firstname = req.body.firstname;
const lastname = req.body.lastname;
const user = new User();
user.username = username;
user.password = password;
user.firstname = firstname;
user.lastname = lastname;
await user.save();
//Set user balance(random)
let userBalance = 0;
let userAdded = await User.findOne({username:username});
if(userAdded){
userAdded = userAdded["_doc"];
const {_id} = userAdded;
userBalance = await setRandomBalance(_id);
}else{
throw new Error("User not found in DB after signing up");
}
res.status(201).json({
msg:"User created successfully",
balance:userBalance
})
}catch(err){
res.status(503).json({
msg:"User SignUP: Not successful: Internal Error",
err:err.message
})
}
});
router.post("/signin", validUserCheck, async (req,res)=>{
req.session.username = req.body.username
try{
const username = req.body.username;
const password = req.body.password;
const jwtToken = jwt.sign({username},process.env.SECRET_KEY);
const user = await User.findOne({username});
const userData = {
firstname: user.firstname,
lastname: user.lastname,
}
res.status(200).json({
msg:"User signed in successfully",
token:jwtToken,
userData
})
}catch(err){
res.status(503).json({
msg:"Error occured while signing in the user",
err:err.message,
})
}
});
router.get("/checkLoginStatus",(req,res)=>{
console.log(`session username: ${req.session.username}`);
try{
if(req.session.username != undefined){
res.status(201).json({
isLoggedIn: true,
status:"ok"
})
}else{
res.status(503).json({
isLoggedIn:false,
status:"bad"
})
}
}catch(err){
res.status(504).json({
error:err.message,
route:"checkLoginStatus"
});
}
})
router.use(userAuth);
router.use(checkLoggedIn);
router.put("/" ,async (req, res)=>{
console.log(`session username: ${req.session.username}`);
const zodUserUpdateObject = zod.object({
password:zod.string().optional(),
firstname:zod.string().optional(),
lastname:zod.string().optional(),
}).strict();
try{
const tokenRec = req.headers.authorization.trim().split(" ")[1];
const username = jwt.decode(tokenRec).username;
console.log(`username rec from token in update: ${username}`)
const user = await User.findOne({
username:username
});
const updateDataFormatCheck = zodUserUpdateObject.safeParse(req.body);
// console.log(updateDataFormatCheck);
if(updateDataFormatCheck.success == false){
throw new Error("Invalid data to update in the DB");
}
if(user){
await User.updateOne({_id: user["_id"]},{$set:req.body});
res.status(201).json({
msg:"User data updated successfully",
status:"ok"
})
}else{
throw new Error("User not found to update data in DB");
}
}catch(err){
res.status(403).json({
msg:"Error occured while updating user info",
err:err.message
})
}
})
router.get("/bulk", async(req, res)=>{
console.log(`session username: ${req.session.username}`);
const filter = req.query.filter;
console.log("Filter = "+filter);
try{
const userRes = await User.find({
$or: [
{
firstname: {$regex: filter, $options:"i"}
},
{
lastname: {$regex: filter, $options:"i"}
}
]
});
// Convert cursor to array
console.log(userRes);
if(true){
const filteredData = userRes.map((user)=>{
user = user["_doc"];
const {_id, password, ...userUpdated} = user;
return userUpdated;
});
const filteredDataWithoutUser = filteredData.filter((user)=>user.username != req.session.username);
console.log("User bulk request")
console.log(filteredDataWithoutUser);
res.status(200).json({
filteredData:filteredDataWithoutUser
})
}
}catch(err){
res.status(500).json({
msg:"Something went wrong",
err:err.message
})
}
});
router.get("/logout", (req, res)=>{
try{
req.session.destroy(()=>{
res.clearCookie("connect.sid", {expires: new Date()});
res.status(200).json({
msg:"User logged out successfully"
})
})
}catch(err){
res.status(404).json({
msg:"Error logging you out"
})
}
})
module.exports = {
userRouter: router
}
|
<!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>Cafe Rina</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon">
<style>
section {
text-align: center;
padding: 10%;
margin: 0;
background-size: cover; /* Scale the background image to cover the entire container */
background-position: center; /* Center the background image */
background-repeat: no-repeat; /* Prevent the background image from repeating */
}
section img {
object-fit: contain;
}
section h1 {
font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
}
section a {
text-decoration: none;
color: #eacb92;
text-shadow: 2px 2px 3px #2c2c2a;
}
.menu-category {
cursor: pointer;
}
@media only screen and (min-width: 576px) {
section {
border-radius: 20px;
}
}
</style>
</head>
<body>
<header class="container-fluid">
<div class="custom-col-xsm-11 custom-col-sm-11 col-md-4 col-lg-4">
<div class="logo-icon-container">
<a href="index.html">
<img src="img/cafe-rina-icon.png" alt="Image description">
</a>
</div>
<div class="brand-container">
<h3><a href="index.html">Cafe Rina</a></h3>
</div>
</div>
<nav class="custom-col-xsm-1 custom-col-sm-1 col-sm-2 col-md-8 col-lg-8">
<div class="hamburger">
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
</div>
<div>
<ul class="menu">
<li><a href="index.html">Home</a></li>
<li><a href="menu.html" style="text-decoration: underline; text-decoration-thickness: 3px;">Menu</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
<ul class="hidden-menu">
<li><a href="index.html">Home</a></li>
<li><a href="menu.html" style="text-decoration: underline; text-decoration-thickness: 3px;">Menu</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</nav>
</header>
<main class="menu-main">
<section class="container menu-category" data-url="menu/espresso.html" style="background-image: linear-gradient(to bottom, #2c2c2a, rgba(255, 255, 255, 0.1)), url('img/menu-espresso.jpg');">
<h1><a href="menu/espresso.html">Espresso</a></h1>
</section>
<section class="container menu-category" data-url="menu/signature-frappe.html" style="background-image: linear-gradient(to bottom, #2c2c2a, rgba(255, 255, 255, 0.1)), url('img/menu-frappe\ \(2\).jpg');">
<h1><a href="menu/signature-frappe.html">Signature Frappe</a></h1>
</section>
<section class="container menu-category" data-url="menu/refreshing-drinks.html" style="background-image: linear-gradient(to bottom, #2c2c2a, rgba(255, 255, 255, 0.1)), url('img/menu-refreshing-drinks-2.jpg');">
<h1><a href="menu/refreshing-drinks.html">Refreshing Drinks</a></h1>
</section>
<section class="container menu-category" data-url="menu/iced-coffee.html" style="background-image: linear-gradient(to bottom, #2c2c2a, rgba(255, 255, 255, 0.1)), url('img/menu-iced-coffee.jpeg');">
<h1><a href="menu/iced-coffee.html">Iced Coffee</a></h1>
</section>
<section class="container menu-category" data-url="menu/non-coffee.html" style="background-image: linear-gradient(to bottom, #2c2c2a, rgba(255, 255, 255, 0.1)), url('img/menu-non-coffee.jpg');">
<h1><a href="menu/non-coffee.html">Non-Coffee</a></h1>
</section>
</main>
<footer>
<div class="container">
<div class="row">
<div class="max-custom-col-sm-6 col-md-3">
<h5>Careers</h5>
<ul class="list-unstyled">
<li><a href="values.html">Values</a></li>
<li><a href="mission.html">Mission</a></li>
<li><a href="join-our-team.html">Join Our Team</a></li>
</ul>
</div>
<div class="max-custom-col-sm-6 col-md-3">
<h5>Social Impact</h5>
<ul class="list-unstyled">
<li><a href="people.html">People</a></li>
<li><a href="planet.html">Planet</a></li>
</ul>
</div>
<div class="max-custom-col-sm-6 col-md-3">
<h5>Policies</h5>
<ul class="list-unstyled">
<li><a href="FAQ.html">FAQ</a></li>
<li><a href="term-of-use.html">Terms of Use</a></li>
<li><a href="privacy-policy.html">Privacy Policy</a></li>
<li><a href="photo-policy.html">Photo Policy</a></li>
<li><a href="reservation-policy.html">Reservation Policy</a></li>
<li><a href="code-of-conduct.html">Code of Conduct</a></li>
</ul>
</div>
<div class="max-custom-col-sm-6 col-md-3">
<h5>Follow Us</h5>
<ul class="list-unstyled">
<li><i class="fab fa-facebook" style="color: white;"></i> <a href="https://www.facebook.com/caferina.official" target="_blank">Facebook</a></li>
<li><i class="fab fa-twitter" style="color: white;"></i> <a href="#">Twitter</a></li>
<li><i class="fab fa-instagram" style="color: white;"></i> <a href="#">Instagram</a></li>
</ul>
</div>
</div>
<hr>
<p class="text-center">© 2023 Cafe Rina. All rights reserved.</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
<script>
const hamburger = document.querySelector('.hamburger');
const menu = document.querySelector('.hidden-menu');
const clickableDivs = document.querySelectorAll('.menu-category');
hamburger.addEventListener('click', () => {
hamburger.classList.toggle('active');
menu.classList.toggle('active');
if (hamburger.classList.contains('active')) {
menu.style.display = 'block';
} else {
menu.style.display = 'none';
}
});
clickableDivs.forEach(div => {
div.addEventListener('click', function() {
const url = div.dataset.url;
window.location.href = url;
});
});
</script>
</body>
</html>
|
# Hooks
Hooks ermöglichen es, einen Code-Snippet in vordefinierten Situationen auszuführen.
Sie sind nur im interaktiven Modus verfügbar [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop), sie funktionieren nicht, wenn eine Nushell mit einem Skript `(nu script.nu`) oder dem Befehl `(nu -c "print foo`") Argument ausgefüht wird.
Derzeit unterstützen wir diese Arten von Hooks:
- `pre_prompt` : Ausgelöst bevor die Eingabeaufforderung gezeichnet wird
- `pre_execution` : Ausgelöst vor dem Ausführen der Zeileneingabe
- `env_change`: Ausgelöst, wenn sich eine Umgebungsvariable ändert
- `display_output` : Ein Block, an den die Ausgabe weitergeleitet wird (experimental.)
- `command_not_found` : Ausgelöst, wenn ein Befehl nicht gefunden wird.
Der Nushell Ausführungszyklus macht es klarer.
Die Schritte zur Auswertung einer Zeile im REPL-Modus sind wie folgt:
1. Prüfe auf `pre_prompt` Hooks und führe diese aus.
1. Prüfe auf `env_change` Hooks und führe diese aus.
1. Stelle die Eingabeaufforderung dar und warte auf eine Benutzer-Eingabe.
1. Nachdem der Benutzer etwas eingegeben und "Enter" gedrückt hat: Prüfe auf `pre_execution` Hooks und führe diese aus.
1. Parse und werte die Benutzer Eingabe aus.
1. Wurde ein Befehl nicht gefunden: Prüfe auf `command_not_found` Hooks. Wenn dieser Text zurückgibt, zeige ihn.
1. Wenn `display_output` definiert ist, verwende diesen um die Ausgabe zu erstellen.
1. Beginne wieder mit 1.
## Grundsätzliches zu Hooks
Um Hooks zu aktivieren, werden sie in der [config](configuration.md) definiert:
```
$env.config = {
# ...other config...
hooks: {
pre_prompt: { print "pre prompt hook" }
pre_execution: { print "pre exec hook" }
env_change: {
PWD: {|before, after| print $"changing directory from ($before) to ($after)" }
}
}
}
```
Bewegen wir uns mit obiger Konfiguration im Dateisystem, wird beim Ändern eines Verzeichnisses die `PWD` Umgebungsvariable verändert.
Die Änderung löst den Hook aus und tauscht die entsprechenden Werte in `before` und `after` aus.
Anstatt nur einen einzigen Hook pro Trigger zu definieren, ist es möglich, eine *Liste von Hooks* zu definieren, die nacheinander durchlaufen werden:
```
$env.config = {
...other config...
hooks: {
pre_prompt: [
{ print "pre prompt hook" }
{ print "pre prompt hook2" }
]
pre_execution: [
{ print "pre exec hook" }
{ print "pre exec hook2" }
]
env_change: {
PWD: [
{|before, after| print $"changing directory from ($before) to ($after)" }
{|before, after| print $"changing directory from ($before) to ($after) 2" }
]
}
}
}
```
Auch könnte es praktischer sein, die bestehende Konfiguration mit neuen Hooks zu aktualisieren,
anstatt die gesamte Konfiguration von Grund auf neu zu definieren:
```
$env.config = ($env.config | upsert hooks {
pre_prompt: ...
pre_execution: ...
env_change: {
PWD: ...
}
})
```
## Changing Environment
Eine Besonderheit der Hooks ist, dass sie die Umgebung bewahren.
Umgebungsvariablen im Hook **Block** werden in ähnlicher Weise wie [`def --env`](environment.md#defining-environment-from-custom-commands) erhalten.
Folgendes Beispiel zeigt dies:
```
> $env.config = ($env.config | upsert hooks {
pre_prompt: { $env.SPAM = "eggs" }
})
> $env.SPAM
eggs
```
Die Hookblöcke folgen ansonsten den allgemeinen Scoping-Regeln, d.h. Befehle, Aliase, etc., die innerhalb des Blocks definiert sind,
werden verworfen, sobald der Block endet.
## Conditional Hooks
Nun wäre es verlockend eine Umgebung zu aktivieren wenn in ein Verzeichnis eingestiegen wird:
```
$env.config = ($env.config | upsert hooks {
env_change: {
PWD: [
{|before, after|
if $after == /some/path/to/directory {
load-env { SPAM: eggs }
}
}
]
}
})
```
Dies wird jedoch nicht funktionieren, weil die Umgebung nur innerhalb des Blocks [`if`](/Befehle/docs/if.md) aktiv ist.
In diesem Fall könnte es als `load-env` neu geschrieben werden (`load-env (if $after == ... { ... } else { {} })`),
aber dieses Muster ist ziemlich häufig und später werden wir sehen, dass nicht alle Fälle so geschrieben werden können.
Um das obige Problem zu lösen, führen wir eine neue Möglichkeit ein, einen Hook zu definieren -- **einen record**:
```
$env.config = ($env.config | upsert hooks {
env_change: {
PWD: [
{
condition: {|before, after| $after == /some/path/to/directory }
code: {|before, after| load-env { SPAM: eggs } }
}
]
}
})
```
Wird der Hook getriggert, wird der `condition` Block ausgewertet.
Wenn dieser `true` zurückgibt, wird der `code` Block ausgewertet.
Wenn er `false`zurückgibt, passiert nichts.
Gibt er etwas anderes zurück, wird ein Fehler generiert.
Das `condition` Feld kann auch weggelassen werden, womit der Hook immer ausgewertet wird.
Die `pre_prompt` und `pre_execution` Hook Typen unterstützen die Conditional Hooks, jedoch nicht die `before` und `after` Parameter.
## Hooks als Strings
Bisher wurde ein Hook als Block definiert, der nur die Umgebung bewahrt, aber nichts anderes.
Um Befehle oder Aliase definieren zu können, ist es möglich, das Codefeld **als string** zu definieren.
Dies funktioniert, als ob der String in den REPL eingeben und Enter gedrückt wird.
So kann der Hook aus dem vorherigen Abschnitt auch geschrieben werden als:
```
> $env.config = ($env.config | upsert hooks {
pre_prompt: '$env.SPAM = "eggs"'
})
> $env.SPAM
eggs
```
Dieses Feature kann z.B. verwendet werden, um abhängig vom aktuellen Verzeichnis Definitionen einzubringen:
```
$env.config = ($env.config | upsert hooks {
env_change: {
PWD: [
{
condition: {|_, after| $after == /some/path/to/directory }
code: 'def foo [] { print "foo" }'
}
{
condition: {|before, _| $before == /some/path/to/directory }
code: 'hide foo'
}
]
}
})
```
Wird ein Hook als String definiert, werden die `$before` und `$after` Variablen auf die vorherigen und aktuellen Umgebungsvariablen gesetzt,
analog dem vorherigen Beispiel:
```
$env.config = ($env.config | upsert hooks {
env_change: {
PWD: {
code: 'print $"changing directory from ($before) to ($after)"'
}
}
}
```
## Beispiele
### Einen einzelnen Hook zur bestehenden Konfiguration hinzufügen
Beispiel eines PWD env Wechsel Hooks:
```
$env.config = ($env.config | upsert hooks.env_change.PWD {|config|
let val = ($config | get -i hooks.env_change.PWD)
if $val == $nothing {
$val | append {|before, after| print $"changing directory from ($before) to ($after)" }
} else {
[
{|before, after| print $"changing directory from ($before) to ($after)" }
]
}
})
```
### Automatisch eine Umgebung aktivieren, wenn ein Verzeichnis betreten wird
Dieses Beispiel sucht nach einem `test-env.nu` in einem Verzeichnis
```
$env.config = ($env.config | upsert hooks.env_change.PWD {
[
{
condition: {|_, after|
($after == '/path/to/target/dir'
and ($after | path join test-env.nu | path exists))
}
code: "overlay use test-env.nu"
}
{
condition: {|before, after|
('/path/to/target/dir' not-in $after
and '/path/to/target/dir' in $before
and 'test-env' in (overlay list))
}
code: "overlay hide test-env --keep-env [ PWD ]"
}
]
})
```
### Filtern oder Umlenken des Befehl-Outputs
Der `display_output` Hook kann verwendet werden, um die Ausgabe von Befehlen umzuleiten.
Ein Block sollte so definiert werden, dass er mit allen Werttypen funktioniert.
Die Ausgabe externer Befehle wird nicht durch `display_output` gefiltert.
Dieser Hook kann die Ausgabe in einem separaten Fenster anzeigen,
vielleicht als HTML-Text. Hier ist die Grundidee, wie dies erreicht wird:
```
$env.config = ($env.config | upsert hooks {
display_output: { to html --partial --no-color | save --raw /tmp/nu-output.html }
})
```
Das Ergebnis wird in der Datei:///tmp/nu-output.html ersichtlich in einem Webbrowser.
Natürlich ist dies nicht sehr praktisch, es sei denn, der Browser wird automatisch neu geladen, wenn sich die Datei ändert.
Anstelle des Befehls [`save`](/commands/docs/save.md) würde normalerweise der HTML-Ausgang an ein gewünschtes Fenster gesendet.
### `command_not_found` Hook in _Arch Linux_
Der folgende Hook verwendet den `pkgfile` Befehl, um in _Arch Linux_ herauzufinden, zu welchem Packet ein Befehl gehört.
```
$env.config = {
...other config...
hooks: {
...other hooks...
command_not_found: {
|cmd_name| (
try {
let pkgs = (pkgfile --binaries --verbose $cmd_name)
if ($pkgs | is-empty) {
return null
}
(
$"(ansi $env.config.color_config.shape_external)($cmd_name)(ansi reset) " +
$"may be found in the following packages:\n($pkgs)"
)
}
)
}
}
}
```
|
package com.nuvola.myproject.client.web.widget.message.event;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
import com.nuvola.myproject.client.web.widget.message.Message;
public class CloseMessageEvent extends GwtEvent<CloseMessageEvent.MessageCloseHandler> {
public interface MessageCloseHandler extends EventHandler {
void onCloseMessage(CloseMessageEvent event);
}
public static Type<MessageCloseHandler> TYPE = new Type<MessageCloseHandler>();
private final Message message;
public static Type<MessageCloseHandler> getType() {
return TYPE;
}
public static void fire(HasHandlers source, Message message) {
source.fireEvent(new CloseMessageEvent(message));
}
public CloseMessageEvent(Message message) {
this.message = message;
}
@Override
public Type<MessageCloseHandler> getAssociatedType() {
return TYPE;
}
public Message getMessage() {
return message;
}
@Override
protected void dispatch(MessageCloseHandler handler) {
handler.onCloseMessage(this);
}
}
|
/*
* Copyright 2020-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package securityclientserver.authorization;
import org.springframework.security.oauth2.client.endpoint.AbstractOAuth2AuthorizationGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
/**
* @author Steve Riesenberg
* @since 1.1
*/
/**
* 디바이스 그랜트 유형 토큰 요청에 사용되는 요청값
*/
public class OAuth2DeviceGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final String deviceCode;
public OAuth2DeviceGrantRequest(ClientRegistration clientRegistration, String deviceCode){
super(AuthorizationGrantType.DEVICE_CODE, clientRegistration);
Assert.hasText(deviceCode, "deviceCode cannot be empty");
this.deviceCode = deviceCode;
}
public String getDeviceCode(){
return this.deviceCode;
}
}
|
from ase.optimize import FIRE
from ase.io import write
from ase.neb import interpolate
from ase.units import kJ, mol
from pathlib import Path
import re
from configparser import ConfigParser, ExtendedInterpolation
from tqdm.notebook import tqdm_notebook as tqdm
# USER
from grrmpy.calculator import pfp_calculator
from grrmpy.neb.functions import find_local_minimum_points_and_ea,get_appropriate_nimages,get_imax
from grrmpy.functions import partially_overlapping_groupings
from grrmpy.neb.repetitive_neb import RepetitiveNEB
from grrmpy.opt.repetitive_opt import RepetitiveOpt
from grrmpy.io.html import write_html
from grrmpy.geometry.functions import get_bond_diff
from grrmpy.path.create_reactpath import create_reactpath
from grrmpy.automate.queue import Queue
from grrmpy.io.read_traj import read_traj
try:
from grrmpy.optimize import FIRELBFGS
DEFAULT_OPTIMIZER = FIRELBFGS
except:
from ase.optimize import LBFGS
DEFAULT_OPTIMIZER = LBFGS
def is_similar(atoms1,atoms2,energy_dif=10,bond_dif=(1,1.0),mult=1,**kwargs):
"""atoms1とatoms2を同一構造とみなすか(NEBでつなぐ必要はないか?)
PinNEBの引数:isomorphism_funcのための関数
基本的には結合状態が同じ且つ,エネルギー差がenergy_dif(kJ/mol)以下であれば同一構造とみなす.
また,bond_dif[0] 本以下の結合状態の違いであり,その結合の差がbond_dif[1] Å以下の時も同一構造とする.
Parameters:
atoms1: Atoms
Atomsオブジェクト
atoms2: Atoms:
Atomsオブジェクト
energy_dif: float
同じ結合状態かつ,エネルギー差がenergy_dif(kJ/mol)の時,同一構造とする
bond_dif: Tuple[int,flaot]
| 1要素目は許容できる結合の差(結合本数)
| 2要素目は結合状態の異なる部分の許容できる結合距離の差(Å)
"""
energy1 = get_energy(atoms1)
energy2 = get_energy(atoms2)
if abs(energy1-energy2)*mol/kJ > energy_dif:
# energy_dif以下のエネルギーであるか
return False
formation, cleavage = get_bond_diff(atoms1,atoms2,mult=mult,**kwargs)
if len((dif_idx:=formation+cleavage))>bond_dif[0]:
# bond_dif[0]以下の結合状態の違いでしかないか
return False
for a_idx,b_idx in dif_idx:
d1 = atoms1.get_distance(a_idx,b_idx)
d2 = atoms2.get_distance(a_idx,b_idx)
if abs(d1-d2)>bond_dif[1]:
return False
return True
def get_energy(atoms,calc_func=pfp_calculator)->float:
try:
return atoms.get_potential_energy()
except RuntimeError:
atoms.calc = calc_func()
return atoms.get_potential_energy()
class AutoPinNEB():
def __init__(self,
eq_list,
connections,
constraints=[], # connectionsには??などがあってはならない
parallel=True,
mic=None,
priority=0,
maxjob = 20,
calc_func=pfp_calculator,
eq_folder="EQ_List",
ts_folder="TS_List",
images_folder="Images",
unconv_folder="unconv",
logfolder = "log",
error_file="ERROR",
path_file="AllPath.dat"):
self.eq_list = eq_list
self.connections = connections
self.constraints = constraints
self.parallel = parallel
self.priority = priority
self.maxjob = maxjob
self.calc_func = calc_func
self.eq_folder = eq_folder
self.ts_folder = ts_folder
self.images_folder = images_folder
self.unconv_folder = unconv_folder
self.logfolder = logfolder
for folder in [self.eq_folder,self.ts_folder,self.images_folder,self.unconv_folder,self.logfolder]:
self.mkdir(folder)
self.error_file = error_file
self.path_file = path_file
self.eqs = [] # 最適化後のEQのリスト
self.tss = [] # 最適化後のTSのリスト
self.path_txt = [] # List[List[str]]
self.path_title = []
if mic is None:
mic = True if any(self.eq_list[0].get_pbc()) else False
self.mic = mic
self.param = self.default_params
self.set_param(**self.param)
self.preneb: RepetitiveNEB
self.neb: RepetitiveNEB
self.opt: DEFAULT_OPTIMIZER
@property
def default_params(self):
return {
"separate_completely":True,
"minenergy":10,
"barrier_less":0,
"nimages":(0.2,32,12),
"isomorphism_func":is_similar,
"rename_preneb_file":True,
"preneb_optimizer":FIRE,
"preneb_climb_list":[False,False,False,False,False],
"preneb_maxstep_list":[0.02,0.05,0.1,0.2,0.25],
"preneb_automaxstep_climb_false":{1:0.05, 0.5:0.1, 0.1:0.2, 0.05:0.3, 0:0.35},
"preneb_automaxstep_climb_true":{0.1:0.03,0:0.01},
"preneb_fmax_list":[30,5,1,0.3,0.1],
"preneb_steps_list":[500,500,500,500,500],
"preneb_kwargs":{},
"prenebopt_kwargs":{},
"neb_optimizer":FIRE,
"neb_climb_list":[False,False,False,False,True,True],
"neb_maxstep_list":[0.02,0.05,0.1,None,0.01,None],
"neb_automaxstep_climb_false":{1:0.05, 0.5:0.1, 0.1:0.2, 0.05:0.3, 0:0.35},
"neb_automaxstep_climb_true":{0.1:0.03,0:0.01},
"neb_fmax_list":[0.01,0.05,0.05,0.05,0.05,0.05],
"neb_steps_list":[100,200,200,2000,500,1500],
"neb_kwargs":{},
"nebopt_kwargs":{},
"opt_optimizer":DEFAULT_OPTIMIZER,
"opt_maxstep_list":[0.02,0.05,0.1,0.2],
"opt_automaxstep":{1:0.1, 0.5:0.2, 0.1:0.3, 0.05:0.4, 0:0.5},
"opt_fmax_list":[0.001,0.001,0.001,0.001],
"opt_steps_list":[50,100,300,10000],
"opt_kwargs":{},
"same_energy_and_fmax_arg":{"times":10,"row":2,"force_digit":4,"energy_digit":6},
"steep_peak_arg":{"max_ea":800, "nsteps":100},
}
@property
def preneb_param(self):
attrs = ["preneb_optimizer", "preneb_climb_list", "preneb_maxstep_list",
"preneb_automaxstep_climb_false", "preneb_automaxstep_climb_true",
"preneb_fmax_list", "preneb_steps_list", "preneb_kwargs",
"prenebopt_kwargs","same_energy_and_fmax_arg","steep_peak_arg"]
keys = ["base_optimizer", "climb_list", "maxstep_list",
"automate_maxstep_false", "automate_maxstep_true",
"fmax_list", "steps_list", "neb_kwargs",
"opt_kwargs","same_energy_and_fmax_arg","steep_peak_arg"]
return {key:self.param[attr] for attr,key in zip(attrs,keys)}
@property
def neb_param(self):
attrs = ["neb_optimizer", "neb_climb_list", "neb_maxstep_list",
"neb_automaxstep_climb_false", "neb_automaxstep_climb_true",
"neb_fmax_list", "neb_steps_list", "neb_kwargs",
"nebopt_kwargs","same_energy_and_fmax_arg","steep_peak_arg"]
keys = ["base_optimizer", "climb_list", "maxstep_list",
"automate_maxstep_false", "automate_maxstep_true",
"fmax_list", "steps_list", "neb_kwargs",
"opt_kwargs","same_energy_and_fmax_arg","steep_peak_arg"]
return {key:self.param[attr] for key,attr in zip(keys,attrs)}
@property
def opt_param(self):
attrs = ["opt_optimizer", "opt_maxstep_list", "opt_automaxstep","opt_fmax_list",
"opt_steps_list", "opt_kwargs"]
keys = ["optimizer","maxstep_list","automate_maxstep","fmax_list","steps_list",
"opt_kwargs"]
return {key:self.param[attr] for key,attr in zip(keys,attrs)}
def set_param(self,**param):
default_params = self.param
unexpected_argument = set(param)-set(default_params)
if len(unexpected_argument) != 0:
raise Exception(f"予期しない引数({', '.join(unexpected_argument)})が存在します.\n"+
f"'self.default_params??'で引数を確認できます\n"
f"Parameters:\n{', '.join(self.default_params.keys())}")
self.param.update(param)
for key,val in default_params.items():
setattr(self, key, val)
def get_param(self):
"""
Parameters:
separate_completely: bool
| 通常のNEBで収束した時,エネルギーダイアグラム上に極小点があれば,極小点を最適化してNEB分割する.
minenergy: float
| minenergy(kJ/mol)以下の活性化エネルギーの場合は極小点があっても無視する.
barrier_less: float
| barrier_less(kJ/mol)以下の活性化エネルギーの場合,バリアレスとみなす.
nimages: int or tuple
| intので指定した場合,指定した数のイメージ数で新たなNEBイメージを作成する.
| tupleで指定する場合,3要素(a,b,c)のタプルを与える.
| aÅ毎にイメージを作成する.最大でもb個,最低でもc個のイメージを作成する.
isomorphism_func: function object
| 同一構造判定を行なう関数,デフォルトではis_similarを用いる.
rename_preneb_file: bool
| Trueの場合,pre_NEBファイルは消す
preneb_optimizer: Optimizer
PreNEBのOptimizer
preneb_climb_list: list of bool
| climbのリスト
preneb_maxstep_list: list of float
| maxstepのリスト
preneb_automaxstep_climb_false:
| {1:0.05, 0.5:0.1, 0.1:0.2, 0.05:0.3, 0:0.35}
preneb_automaxstep_climb_true: dict
{0.1:0.03,0:0.01}
preneb_fmax_list :list of float
|
preneb_steps_list: list of int
|
preneb_kwargs:
|
prenebopt_kwargs:
|
neb_optimizer: Optimizer
|
"neb_climb_list": list of bool
|
neb_maxstep_list:
| [0.02,0.05,0.1,None,0.01,None],
neb_automaxstep_climb_false:
| {1:0.05, 0.5:0.1, 0.1:0.2, 0.05:0.3, 0:0.35},
neb_automaxstep_climb_true":
| {0.1:0.03,0:0.01},
neb_fmax_list:
| [0.01,0.05,0.05,0.05,0.05,0.05],
neb_steps_list:
| [100,200,200,2000,500,1500],
neb_kwargs:
| {}
nebopt_kwargs:
| {}
opt_optimizer:
| DEFAULT_OPTIMIZER
opt_maxstep_list:
| [0.02,0.05,0.1,0.2]
opt_automaxstep:
| {1:0.1, 0.5:0.2, 0.1:0.3, 0.05:0.4, 0:0.5}
opt_fmax_list:
| [0.001,0.001,0.001,0.001]
opt_steps_list:
| [50,100,300,10000]
opt_kwargs:
| {}
same_energy_and_fmax_arg:
| {"times":10,"row":2,"force_digit":4,"energy_digit":6},
steep_peak_arg:
| {"max_ea":800, "nsteps":100}
"""
return self.param
def mkdir(self,folder):
p = Path(folder)
if not p.exists():
p.mkdir()
def rename(self,old_name,new_name,extention_list=["traj","html","log"]):
for extention in extention_list:# prenebのReName
Path(f"{old_name}.{extention}").rename(f"{new_name}.{extention}")
def register_eqs(self,atoms):
self.eqs.append(atoms)
eq_num = len(self.eqs)-1
write(f"{self.eq_folder}/{eq_num}.traj",atoms)
return eq_num
def register_tss(self,images,name,i,ini_idx,fin_idx): # ts_idx GRRMのTS番号
imax = get_imax(images,self.barrier_less,self.calc_func)
if imax is not None: # バリアレスでない場合
ts = images[imax]
self.tss.append(ts)
write(f"{self.ts_folder}/{len(self.tss)-1}.traj",ts)
new_path_txt = self.make_path_txt(self.path_txt[i],ini_idx,fin_idx,len(self.tss)-1)
else: # バリアレスの場合
new_path_txt = self.make_path_txt(self.path_txt[i],ini_idx,fin_idx,None)
self.path_txt[i] = new_path_txt
self.write_path(i)
write(f"{self.images_folder}/{name}.traj",images)
def get_energy(self,atoms):
try:
return atoms.get_potential_energy()
except:
atoms.calc = self.calc_func()
return atoms.get_potential_energy()
def make_images_and_canc_dH(self,ini_idx,fin_idx,n):
"""imageを作成する
n: 指定方法は2種類ある
int: n個のイメージで作成する
Tuple(dist,max_n,min_n)
"""
ini = self.eqs[ini_idx]
fin = self.eqs[fin_idx]
if type(n)!=int:
n = get_appropriate_nimages(ini,fin,n[0],n[1],n[2],self.mic)
images = [ini.copy() for _ in range(n+1)]+[fin.copy()]
dH = abs(self.get_energy(ini)-self.get_energy(fin))
interpolate(images,mic=self.mic)
return images, dH # この地点ではCalculatorもConstraintsも設定していない
def _first_push(self,i,ini_idx,fin_idx):
ini_atoms = self.eqs[ini_idx]
fin_atoms = self.eqs[fin_idx]
if self.isomorphism_func(ini_atoms,fin_atoms):
return [] # ini,finが同じ構造だった時
self.mkdir(f"{self.logfolder}/{i}")
images,dH = self.make_images_and_canc_dH(ini_idx,fin_idx,self.nimages)
self.write_path(i)
return [[-dH,[ini_idx,fin_idx,0],images,i]]
def make_first_push(self,i,ini_idx,fin_idx):
return lambda ini_idx=ini_idx,fin_idx=fin_idx: self._first_push(i,ini_idx,fin_idx)
def run_and_push(self,data,layer):
_,[ini_idx,fin_idx,width],images,i = data
folder = f"{self.logfolder}/{i}"
preneb_name = f"pre_EQ{ini_idx}-EQ{fin_idx}({layer}-{width})"
neb_name = f"EQ{ini_idx}-EQ{fin_idx}({layer}-{width})"
_, images,minimum_point = self.run_neb(images,f"{folder}/{preneb_name}",preneb=True) # PreNEB
if len(minimum_point) > 0:
# 極小値がある場合
eq_num_list, atoms_list = self.run_opts(images,minimum_point,f"{folder}/opt_{preneb_name}",nabname=f"{folder}/{preneb_name}") # 構造最適化とEQの保存
eq_num_list = [ini_idx] + eq_num_list + [fin_idx]
atoms_list = [images[0]] + atoms_list + [images[-1]]
push_data = self.make_push_data(eq_num_list,atoms_list,i) # 新たなImagesを作成
return push_data
else:
if self.rename_preneb_file: # pre_NEBのrename
self.rename(f"{folder}/{preneb_name}",f"{folder}/{neb_name}")
converged,images,minimum_point = self.run_neb(images,f"{folder}/{neb_name}") # PreNEB
if len(minimum_point) > 0:
if not converged or self.separate_completely:
eq_num_list, atoms_list = self.run_opts(images,minimum_point,f"{folder}/opt_{neb_name}",nabname=f"{folder}/{neb_name}") # 構造最適化とEQの保存
eq_num_list = [ini_idx] + eq_num_list + [fin_idx]
atoms_list = [images[0]] + atoms_list + [images[-1]]
push_data = self.make_push_data(eq_num_list,atoms_list,i) # 新たなImagesを作成
return push_data
else:
self.register_tss(images,f"{i}_EQ{ini_idx}-EQ{fin_idx}({layer}-{width})",i,ini_idx,fin_idx)
return []
else:
if converged:
self.register_tss(images,f"{i}_EQ{ini_idx}-EQ{fin_idx}({layer}-{width})",i,ini_idx,fin_idx)
return []
else:
write(f"{self.unconv_folder}/({i}){neb_name}.traj",images) # 未収束の保存
return []
def write_path(self,i):
path_path = f"{self.logfolder}/{i}/Path.dat"
with open(path_path,"w") as f:
f.write("[Dir]\n")
f.write(f"EQ: ./{self.eq_folder}/\n")
f.write(f"TS: ./{self.ts_folder}/\n")
f.write(f"[{self.path_title[i]}]\n")
f.write(f"path: {self.path_txt[i]}\n")
path_obj = create_reactpath(path_path)
path_obj.write_html(f"{self.logfolder}/{i}/Path.html")
def write_all_path(self):
p = Path(self.path_file)
with open(p,"w") as f:
f.write("[Dir]\n")
f.write(f"EQ: ./{self.eq_folder}/\n")
f.write(f"TS: ./{self.ts_folder}/\n")
for title,path in zip(self.path_title,self.path_txt):
f.write(f"[{title}]\n")
f.write(f"path: {path}\n")
paths_obj = create_reactpath(self.path_file)
paths_obj.write_html(outfile=p.with_suffix(".html"))
def make_path_txt(self,path_txt,ini_name,fin_name,add_data):
"""
path_txt: 現在のpath_txt
add_data: str
EQを追加する
add_data: int:
TSを追加する
add_data: None
バリアレスを追加
"""
if add_data is None:
new_path_txt = re.sub(f"(EQ{ini_name}).(EQ{fin_name})",f"\\1~\\2",path_txt)
elif type(add_data) == int:
new_path_txt = re.sub(f"(EQ{ini_name}).(EQ{fin_name})",f"\\1;TS{add_data};\\2",path_txt)
elif type(add_data)==str:
new_path_txt = re.sub(f"EQ{ini_name}.EQ{fin_name}",f"{add_data}",path_txt)
return new_path_txt
def before_run(self,restart:int):
if restart != 0:
config = ConfigParser(interpolation= ExtendedInterpolation())
config.optionxform = str # キーが小文字になることを防ぐ
config.read(self.path_file, encoding='utf-8')
title_list = config.sections()
if "Dir" in title_list:
title_list.remove("Dir")
self.path_title = title_list
self.path_txt = [config[title]["path"] for title in title_list]
self.eqs,_ = read_traj(self.eq_folder)
self.tss,_ = read_traj(self.ts_folder)
else:
for i in range(len(self.eq_list)):
write(f"{self.eq_folder}/{i}.traj",self.eq_list[i])
self.eqs.append(self.eq_list[i])
self.path_title = [f"{ts_idx}(EQ{ini_idx}-EQ{fin_idx})" for ts_idx,(ini_idx,fin_idx)
in enumerate(self.connections[restart:],start=restart)]
self.path_txt = [f"EQ{ini_idx};EQ{fin_idx}"
if self.isomorphism_func(self.eqs[ini_idx],self.eqs[fin_idx])
else f"EQ{ini_idx}|EQ{fin_idx}"
for ini_idx,fin_idx in self.connections[restart:]]
self.write_all_path()
def run_neb(self,images,name,preneb=False,):
self.neb = RepetitiveNEB(images,self.constraints,self.parallel,self.mic,self.calc_func,name)
self.neb.attach(lambda:write_html(f"{name}.html",self.neb.images))
self.neb.attach(lambda:write(f"{name}.traj",self.neb.images))
param = self.preneb_param if preneb else self.neb_param
converged = self.neb.run(**param)
minimum_point,_ = find_local_minimum_points_and_ea(self.neb.images,minenergy=self.minenergy)
write_html(f"{name}.html",self.neb.images,highlight=minimum_point)
return converged,self.neb.images,minimum_point
def run_opt(self,atoms,name):
self.opt = RepetitiveOpt(atoms,self.constraints,name,self.calc_func)
param = self.opt_param
converged = self.opt.run(**param)
eq_num = self.register_eqs(self.opt.atoms) if converged else None
return [eq_num,self.opt.atoms] # 収束した場合eq_num=EQ番号,未収束の場合None
def run_opts(self,images,minimum_point,name,nabname):
# 最適化を行なう. [EQ番号] 未収束の場合EQ番号はNoneが入る
eq_num_list,atoms_list,minimum_point = zip(*[self.run_opt(images[idx],f"{name}-({idx}).log")+[idx] for idx in minimum_point])
write_html(f"{nabname}.html",images,highlight=minimum_point,
annotation=[(i,f"Succeed-->EQ{eq_num}" if eq_num is not None else "Failed")
for i,eq_num in zip(minimum_point,eq_num_list)])
return list(eq_num_list), list(atoms_list)
def make_push_data(self,eq_num_list, atoms_list,ts_idx): # ts_idxはGRRM上のTS番号
push_data = []
path_txt = f"EQ{eq_num_list[0]}"
for i,((ini_eq_num,ini_atoms),(fin_eq_num,fin_atoms)) in enumerate(partially_overlapping_groupings(zip(eq_num_list,atoms_list),2,1)):
if not self.isomorphism_func(ini_atoms,fin_atoms): # 違う構造の時
images,dH = self.make_images_and_canc_dH(ini_eq_num,fin_eq_num,self.nimages)
push_data.append([-dH,[ini_eq_num,fin_eq_num,i],images,ts_idx])
path_txt += f"|EQ{fin_eq_num}"
else:
path_txt += f";EQ{fin_eq_num}"
new_path_txt = self.make_path_txt(self.path_txt[ts_idx],eq_num_list[0],eq_num_list[-1],path_txt)
self.path_txt[ts_idx] = new_path_txt
self.write_path(ts_idx)
return push_data
def run(self,restart:int=0):
self.before_run(restart)
for i,(ini_idx,fin_idx) in enumerate(tqdm(self.connections[restart:]),start=restart):
if isinstance(ini_idx,str) or isinstance(fin_idx,str):
continue
self.first_push = self.make_first_push(i,ini_idx,fin_idx)
que = Queue(executor=self,priority=self.priority,maxjob=self.maxjob)
que.run()
self.write_all_path()
if Path("STOP.txt").exists():
Path("STOP.txt").unlink()
break
class PinNEB(AutoPinNEB):
def __init__(self,
images,
constraints=[],
parallel=True,
mic=None,
calc_func=pfp_calculator,
eq_folder="EQ_List",
logfolder = "log",
images_folder="Images_List",
unconv_folder="unconv",
ts_folder="TS_List",
errorfile="ERROR",
path_html="Path.html",
path_dat = "Path.dat",
priority = 0,
maxjob = 20,):
self.images = images
self.constraints = constraints
self.parallel = parallel
if mic is None:
mic = True if any(images[0].get_pbc()) else False
self.mic = mic
self.calc_func = calc_func
self.eq_folder = eq_folder
self.images_folder = images_folder
self.unconv_folder = unconv_folder
self.ts_folder = ts_folder
self.logfolder = logfolder
self.errorfile = errorfile
self.path_html = path_html
self.path_dat = path_dat
self.priority = priority
self.maxjob = maxjob
self.mkdir(f"{self.logfolder}")
self.mkdir(f"{self.ts_folder}")
self.mkdir(f"{self.eq_folder}")
self.mkdir(f"{self.images_folder}")
self.mkdir(f"{self.unconv_folder}")
self.path_txt = ""
self.eqs = []
self.tss = []
self.param = self.default_params
self.set_param(**self.param)
@property
def default_params(self):
return super().default_params
@property
def preneb_param(self):
return super().preneb_param
@property
def neb_param(self):
return super().neb_param
@property
def opt_param(self):
return super().opt_param
def set_param(self,**param):
super().set_param(**param)
def get_param(self):
return super().get_param()
def register_eqs(self,atoms):
self.eqs.append(atoms)
eq_num = len(self.eqs)-1
write(f"{self.eq_folder}/{eq_num}.traj",atoms)
return eq_num
def register_tss(self,images,name,ini_idx,fin_idx): # ts_idx GRRMのTS番号
imax = get_imax(images,self.barrier_less,self.calc_func)
if imax is not None: # バリアレスでない場合
ts = images[imax]
self.tss.append(ts)
write(f"{self.ts_folder}/{len(self.tss)-1}.traj",ts)
new_path_txt = self.make_path_txt(self.path_txt,ini_idx,fin_idx,len(self.tss)-1)
else: # バリアレスの場合
new_path_txt = self.make_path_txt(self.path_txt,ini_idx,fin_idx,None)
self.path_txt = new_path_txt
self.write_path()
write(f"{self.images_folder}/{name}.traj",images)
def make_path_txt(self,path_txt,ini_name,fin_name,add_data):
"""
path_txt: 現在のpath_txt
add_data: str
EQを追加する
add_data: int:
TSを追加する
add_data: None
バリアレスを追加
"""
if add_data is None:
new_path_txt = re.sub(f"(EQ{ini_name}).(EQ{fin_name})",f"\\1~\\2",path_txt)
elif type(add_data) == int:
new_path_txt = re.sub(f"(EQ{ini_name}).(EQ{fin_name})",f"\\1;TS{add_data};\\2",path_txt)
elif type(add_data)==str:
new_path_txt = re.sub(f"EQ{ini_name}.EQ{fin_name}",f"{add_data}",path_txt)
return new_path_txt
def write_path(self):
with open(self.path_dat,"w") as f:
f.write("[Dir]\n")
f.write(f"EQ: ./{self.eq_folder}/\n")
f.write(f"TS: ./{self.ts_folder}/\n")
f.write(f"[reaction]\n")
f.write(f"path: {self.path_txt}\n")
path_obj = create_reactpath(self.path_dat)
path_obj.write_html(self.path_html)
def first_push(self):
"""必須メソッド"""
self.path_txt = "EQ0|EQ1"
ini = self.images[0]
fin = self.images[-1]
if self.isomorphism_func(ini,fin):
return [] # ini,finが同じ構造だった時
dH = abs(self.get_energy(ini)-self.get_energy(fin))
self.write_path()
return [[-dH,[0,1,0],self.images]]
def make_push_data(self,eq_num_list,atoms_list):
push_data = []
path_txt = f"EQ{eq_num_list[0]}"
for i,((ini_eq_num,ini_atoms),(fin_eq_num,fin_atoms)) in enumerate(partially_overlapping_groupings(zip(eq_num_list,atoms_list),2,1)):
if not self.isomorphism_func(ini_atoms,fin_atoms): # 違う構造の時
images,dH = self.make_images_and_canc_dH(ini_eq_num,fin_eq_num,self.nimages)
push_data.append([-dH,[ini_eq_num,fin_eq_num,i],images])
path_txt += f"|EQ{fin_eq_num}"
else:
path_txt += f";EQ{fin_eq_num}"
new_path_txt = self.make_path_txt(self.path_txt,eq_num_list[0],eq_num_list[-1],path_txt)
self.path_txt = new_path_txt
self.write_path()
return push_data
def run_and_push(self,data,layer):
_,[ini_idx,fin_idx,width],images = data
preneb_name = f"pre_EQ{ini_idx}-EQ{fin_idx}({layer}-{width})"
neb_name = f"EQ{ini_idx}-EQ{fin_idx}({layer}-{width})"
_, images,minimum_point = self.run_neb(images,f"{self.logfolder}/{preneb_name}",preneb=True) # PreNEB
if len(minimum_point) > 0:
# 極小値がある場合
eq_num_list, atoms_list = self.run_opts(images,minimum_point,f"{self.logfolder}/opt_{preneb_name}",nabname=f"{self.logfolder}/{preneb_name}") # 構造最適化とEQの保存
eq_num_list = [ini_idx] + eq_num_list + [fin_idx]
atoms_list = [images[0]] + atoms_list + [images[-1]]
push_data = self.make_push_data(eq_num_list,atoms_list) # 新たなImagesを作成
return push_data
else:
if self.rename_preneb_file: # pre_NEBのrename
self.rename(f"{self.logfolder}/{preneb_name}",f"{self.logfolder}/{neb_name}")
converged,images,minimum_point = self.run_neb(images,f"{self.logfolder}/{neb_name}") # PreNEB
if len(minimum_point) > 0:
if not converged or self.separate_completely:
eq_num_list, atoms_list = self.run_opts(images,minimum_point,f"{self.logfolder}/opt_{neb_name}",nabname=f"{self.logfolder}/{neb_name}") # 構造最適化とEQの保存
eq_num_list = [ini_idx] + eq_num_list + [fin_idx]
atoms_list = [images[0]] + atoms_list + [images[-1]]
push_data = self.make_push_data(eq_num_list,atoms_list) # 新たなImagesを作成
return push_data
else:
self.register_tss(images,f"EQ{ini_idx}-EQ{fin_idx}({layer}-{width})",ini_idx,fin_idx)
return []
else:
if converged:
self.register_tss(images,f"EQ{ini_idx}-EQ{fin_idx}({layer}-{width})",ini_idx,fin_idx)
return []
else:
write(f"{self.unconv_folder}/{neb_name}.traj",images) # 未収束の保存
return []
def run(self):
self.register_eqs(self.images[0])
self.register_eqs(self.images[-1])
que = Queue(executor=self,priority=self.priority,maxjob=self.maxjob)
que.run()
|
//
// This source file is part of the CS342 2023 Allergy Team Application project
//
// SPDX-FileCopyrightText: 2023 Stanford University
//
// SPDX-License-Identifier: MIT
//
import ImageSource
import SwiftUI
public struct AllergyImageSource: View {
@Binding private var image: UIImage?
@State private var showCamera = false
@State private var showPhotosPicker = false
@State private var showImageTracking = false
@State private var imageState: ImageState = .empty
public var body: some View {
imageView
.fullScreenCover(isPresented: $showImageTracking) {
ARImageTrackingOverlay(image: $imageState)
}
.fullScreenCover(isPresented: $showCamera) {
CameraOverlay(image: $imageState)
}
.sheet(isPresented: $showPhotosPicker) {
PhotosPicker(image: $imageState)
}
.onChange(of: imageState) { newImageState in
image = newImageState.image
}
}
@ViewBuilder
private var imageView: some View {
GeometryReader { proxy in
ZStack {
Rectangle()
.foregroundColor(Color(.secondarySystemBackground))
switch imageState {
case .empty:
addMenu(proxy: proxy)
case .loading:
ProgressView()
case .success(let uIImage):
Image(uiImage: uIImage)
.resizable()
.scaledToFill()
.accessibilityLabel(Text("User provided image"))
.frame(width: proxy.size.width, height: proxy.size.height)
removeMenu(proxy: proxy)
case .failure(let imageError):
Text(imageError.localizedDescription)
}
}
}
}
/// <#Description#>
/// - Parameter image: <#image description#>
public init(image: Binding<UIImage?> = Binding(get: { nil }, set: { _ in })) {
self._image = image
}
private func removeMenu(proxy: GeometryProxy) -> some View {
Menu(
content: {
Button(
role: .destructive,
action: {
imageState = .empty
},
label: {
Label("Delete", systemImage: "trash.fill")
}
)
}
, label: {
ZStack {
Rectangle()
.foregroundColor(.clear)
.frame(width: proxy.size.width, height: proxy.size.height)
}
}
)
}
private func addMenu(proxy: GeometryProxy) -> some View {
Menu(
content: {
Button(
action: {
showImageTracking.toggle()
},
label: {
Label("AR Camera", systemImage: "camera.viewfinder")
}
)
Button(
action: {
showCamera.toggle()
},
label: {
Label("Camera", systemImage: "camera.shutter.button")
}
)
Button(
action: {
showPhotosPicker.toggle()
},
label: {
Label("Photo Picker", systemImage: "photo.on.rectangle.angled")
}
)
}
, label: {
ZStack {
Rectangle()
.foregroundColor(.clear)
.frame(width: proxy.size.width, height: proxy.size.height)
Image(systemName: "plus")
.accessibilityLabel(Text("Add Image"))
}
}
)
}
}
struct ImageSource_Previews: PreviewProvider {
@State private static var image: UIImage?
static var previews: some View {
ImageSource(image: $image)
.padding()
}
}
|
package com.haggixago.haggixagoapi.config;
import com.haggixago.haggixagoapi.model.UserAuth;
import com.haggixago.haggixagoapi.repository.UserAuthRepository;
import com.haggixago.haggixagoapi.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserAuthRepository userAuthRepository;
@Autowired
PasswordEncoder encoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<SimpleGrantedAuthority> roles = null;
final UserAuth userAuth = userAuthRepository.findUserAuthByEmail(username);
if (username.equals("[email protected]")) {
roles = Arrays.asList(new SimpleGrantedAuthority("Role_Admin"));
return new User(userAuth.getEmail(), encoder.encode(userAuth.getPassword()), roles);
}
throw new UsernameNotFoundException(username);
}
}
|
<template>
<button :disabled="isRunning" @click="initSuperVizRoom">Join Video Conference</button>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import { v4 as uuidv4 } from "uuid";
import SuperVizRoom from "@superviz/sdk";
import { VideoConference } from "@superviz/sdk/lib/components";
const groupId = "sv-sample-room-vue-t s-video-conference";
const groupName = "Sample Room for Video Conference (Vue/TS)";
const DEVELOPER_KEY = process.env.VUE_APP_SUPERVIZ_DEVELOPER_TOKEN as string;
export default defineComponent({
name: "App",
setup() {
const isRunning = ref(false);
const initSuperVizRoom = async () => {
isRunning.value = true;
const roomId = uuidv4();
const room = await SuperVizRoom(DEVELOPER_KEY, {
roomId: roomId,
group: {
id: groupId,
name: groupName,
},
participant: {
id: "zeus",
name: "Zeus",
},
});
const video = new VideoConference({
participantType: "host",
});
room.addComponent(video);
};
return {
isRunning,
initSuperVizRoom,
};
},
});
</script>
|
import Header from "../../components/Header/Header";
import { sanityClient, urlFor } from "../../sanity";
import { Post } from "../../typings";
import { GetStaticProps } from "next";
import PortableText from "react-portable-text";
import { useForm, SubmitHandler } from "react-hook-form";
import { useState } from "react";
import styles from "../../styles/post/article.module.css";
import Cookies from "universal-cookie";
import rocket from "../../image/logo/rocket_black.png";
import message from "../../image/logo/message_black.png";
import Image from "next/image";
interface IFormInput {
_id: string;
name: string;
email: string;
comment: string;
}
interface Props {
post: Post;
}
function Post({ post }: Props) {
const [submitted, setSubmitted] = useState(false);
const cookies = new Cookies();
const user_uid = cookies.get("user_uid");
const user_data = cookies.get("userData");
const colors = [
"#3f8dd6",
"#3f41d6",
"#b39431",
"#b65353",
"#3fd671"
];
const random = Math.floor(Math.random() * colors.length);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<IFormInput>();
const onSubmit: SubmitHandler<IFormInput> = (data) => {
data["name"] = user_data.user_name
data["email"] = user_data.user_email
fetch("/api/createComment", {
method: "POST",
body: JSON.stringify(data),
})
.then(() => {
setSubmitted(true);
})
.catch((err) => {
console.log(err);
setSubmitted(false);
});
};
return (
<div className={styles.container}>
<Header />
<div>
<div className={styles.test} />
<div style={{ fontSize: 18 }}>
<article className={styles.article}>
<div className={styles.intro_div}>
<img
className={styles.author_pic}
src={urlFor(post.author.image).url()!}
alt=""
/>
<div>
<p className={styles.post_detail}>{post.author.name}</p>
<p className={styles.post_date}>
{new Date(post._createdAt).toLocaleString()}
</p>
</div>
</div>
<h1 className={styles.title}>{post.title}</h1>
<div className="mt-5">
<PortableText
dataset={
process.env.NEXT_PUBLIC_SANITY_PROJECT_ID! || "production"
}
projectId={
process.env.NEXT_PUBLIC_SANITY_PROJECT_ID! || "n6repj5a"
}
content={post.body}
className={styles.paragraphs}
serializers={{
normal_block: (props: any) => (
<div className={styles.paragraphs_normal} {...props} />
),
h1: (props: any) => <h1 className={styles.h1} {...props} />,
h2: (props: any) => <h2 className={styles.h2} {...props} />,
h3: (props: any) => <h3 className={styles.h3} {...props} />,
li: ({ children }: any) => (
<li className={styles.list}>{children}</li>
),
link: ({ href, children }: any) => (
<a href={href} className={styles.link}>
{children}
</a>
),
}}
/>
</div>
</article>
</div>
<hr className="max-w-lg my-5 mx-auto border border-green-500" />
{submitted ? (
<div className={styles.success_comment}>
<h3 className="text-3xl font-bold">
Thank you for submitting your comment!
</h3>
<p>Once it has been approved, it will appear below!</p>
</div>
) : (
<form
onSubmit={handleSubmit(onSubmit)}
className="flex flex-col p-5 max-w-2xl mx-auto mb-10"
>
<h3 className={styles.form_question}>
Is this article helpful for you?
</h3>
<h4 className="text-3xl font-bold">Leave a comment below!</h4>
<hr className="py-3 mt-2" />
{user_uid == undefined && (
<div>
<p className={styles.login_sign}>Log in to leave a comment.</p>
</div>
)}
{user_uid != undefined && (
<div>
<input
{...register("_id")}
type="hidden"
name="_id"
value={post._id}
></input>
<label className="block mb-5">
<span className="text-gray-700">Comment</span>
<textarea
{...register("comment", { required: true })}
className={styles.input_name}
placeholder="Try typing some comments here!"
rows={8}
/>
</label>
<div className="flex flex-col p-5">
{errors.comment && (
<span className="text-red-500">
- The Comment Field Is Required
</span>
)}
</div>
<input type="submit" className={styles.submit_button}></input>
</div>
)}
</form>
)}
<div className={styles.center}>
<p className={styles.comment_header}>Comments</p>
{post.comments.map((comment) => (
<div key={comment._id} className={styles.user_comment}>
<div className={styles.inline}>
<div
className={styles.comment_profile_pic}
style={{ background: `${colors[random]}` }}
>
{comment.name.charAt(0)}
</div>
<p className={styles.user_name}>{comment.name}</p>
</div>
<div className={styles.comment_text_section}>
<p className={styles.comment_text}>{comment.comment}</p>
</div>
<div className={styles.inline}>
<button
className={styles.like_button}
style={{ paddingTop: "0.25em" }}
>
<div className={styles.inline}>
<Image src={rocket} width="22px" height="22px" />
<p className={styles.like_num}>10</p>
</div>
</button>
<button
className={styles.message_button}
style={{ paddingTop: "0.25em" }}
>
<div className={styles.inline}>
<Image src={message} width="22px" height="22px" />
<p className={styles.like_num}>10</p>
</div>
</button>
</div>
</div>
))}
</div>
</div>
</div>
);
}
export default Post;
export const getStaticPaths = async () => {
const query = `*[_type == "post"]{
_id,
slug {
current
},
}`;
const posts = await sanityClient.fetch(query);
const paths = posts.map((post: Post) => {
return {
params: {
slug: post.slug.current,
},
};
});
return {
paths,
fallback: "blocking",
};
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
const query = `*[_type == "post" && slug.current == $slug][0]{
_id,
_createdAt,
title,
author-> {
name,
image
},
'comments': *[
_type == "comment" &&
post._ref == ^._id &&
approved == true],
description,
mainImage,
slug,
body,
}`;
const post = await sanityClient.fetch(query, {
slug: params?.slug,
});
if (!post) {
return {
notFound: true,
};
}
return {
props: {
post,
},
revalidate: 60,
};
};
|
package com.udacity.project4
import android.app.Application
import android.view.View
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider.getApplicationContext
import androidx.test.espresso.Espresso.closeSoftKeyboard
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.PointOfInterest
import com.udacity.project4.locationreminders.RemindersActivity
import com.udacity.project4.locationreminders.data.ReminderDataSource
import com.udacity.project4.locationreminders.data.local.LocalDB
import com.udacity.project4.locationreminders.data.local.RemindersLocalRepository
import com.udacity.project4.locationreminders.reminderslist.RemindersListViewModel
import com.udacity.project4.locationreminders.savereminder.SaveReminderViewModel
import com.udacity.project4.util.DataBindingIdlingResource
import com.udacity.project4.util.monitorActivity
import com.udacity.project4.utils.EspressoIdlingResource
import kotlinx.coroutines.runBlocking
import org.hamcrest.CoreMatchers.not
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import org.koin.test.AutoCloseKoinTest
import org.koin.test.get
@RunWith(AndroidJUnit4::class)
@LargeTest
//END TO END test to black box test the app
class RemindersActivityTest :
AutoCloseKoinTest() {// Extended Koin Test - embed autoclose @after method to close Koin after every test
private lateinit var repository: ReminderDataSource
private lateinit var appContext: Application
private val dataBindingIdlingResource = DataBindingIdlingResource()
/**
* As we use Koin as a Service Locator Library to develop our code, we'll also use Koin to test our code.
* at this step we will initialize Koin related code to be able to use it in out testing.
*/
@Before
fun init() {
stopKoin()//stop the original app koin
appContext = getApplicationContext()
val myModule = module {
viewModel {
RemindersListViewModel(
appContext,
get() as ReminderDataSource
)
}
single {
SaveReminderViewModel(
appContext,
get() as ReminderDataSource
)
}
single { RemindersLocalRepository(get()) as ReminderDataSource }
single { LocalDB.createRemindersDao(appContext) }
}
//declare a new koin module
startKoin {
modules(listOf(myModule))
}
//Get our real repository
repository = get()
//clear the data to start fresh
runBlocking {
repository.deleteAllReminders()
}
IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource)
IdlingRegistry.getInstance().register(dataBindingIdlingResource)
}
@After
fun clean() {
IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource)
IdlingRegistry.getInstance().unregister(dataBindingIdlingResource)
}
@Test
fun createReminder_appearsInRemindersList() {
val activityScenario = ActivityScenario.launch(RemindersActivity::class.java)
dataBindingIdlingResource.monitorActivity(activityScenario)
// Opening SaveReminderFragment
onView(
withId(R.id.addReminderFAB)
).perform(click())
// Entering Reminder Data
onView(
withId(R.id.reminderTitle)
).perform(typeText("Title"))
onView(
withId(R.id.reminderDescription)
).perform(typeText("Description"))
// Setting Location from the view model
val saveReminderViewModel = get<SaveReminderViewModel>()
val poi = PointOfInterest(
LatLng(0.0, 0.0),
"fakeLocation",
"fakeLocation"
)
saveReminderViewModel.addCustomPoi(poi)
closeSoftKeyboard()
// Saving the reminder
onView(
withId(R.id.saveReminder)
).perform(click())
// Then a reminder must appear on the screen with known details
onView(
withText("Title")
).check(matches(isDisplayed()))
onView(
withText("Description")
).check(matches(isDisplayed()))
onView(
withText("fakeLocation")
).check(matches(isDisplayed()))
}
@Test
fun attemptingToSaveReminderWithEmptyTitle_showsErrorSnackbar() {
val activityScenario = ActivityScenario.launch(RemindersActivity::class.java)
dataBindingIdlingResource.monitorActivity(activityScenario)
// Opening SaveReminderFragment
onView(
withId(R.id.addReminderFAB)
).perform(click())
// *** Leaving Title field empty ***
onView(
withId(R.id.reminderDescription)
).perform(typeText("Description"))
// Setting Location from the view model
val saveReminderViewModel = get<SaveReminderViewModel>()
val poi = PointOfInterest(
LatLng(0.0, 0.0),
"fakeLocation",
"fakeLocation"
)
saveReminderViewModel.addCustomPoi(poi)
closeSoftKeyboard()
// When Attempting to save the reminder
onView(
withId(R.id.saveReminder)
).perform(click())
// Then A snackbar with error message should appear
onView(
withText(R.string.err_enter_title)
).check(matches(isDisplayed()))
}
@Test
fun attemptingToSaveReminderWithNoLocation_showsErrorSnackbar() {
val activityScenario = ActivityScenario.launch(RemindersActivity::class.java)
dataBindingIdlingResource.monitorActivity(activityScenario)
// Opening SaveReminderFragment
onView(
withId(R.id.addReminderFAB)
).perform(click())
// Entering Reminder Data
onView(
withId(R.id.reminderTitle)
).perform(typeText("Title"))
onView(
withId(R.id.reminderDescription)
).perform(typeText("Description"))
closeSoftKeyboard()
// When ignoring adding location and save
onView(
withId(R.id.saveReminder)
).perform(click())
// Than snackbar with proper message should appear
onView(
withText(R.string.err_select_location)
).check(matches(isDisplayed()))
}
@Test
fun savingReminder_showsToastMessage() {
val activityScenario = ActivityScenario.launch(RemindersActivity::class.java)
dataBindingIdlingResource.monitorActivity(activityScenario)
// Opening SaveReminderFragment
onView(
withId(R.id.addReminderFAB)
).perform(click())
// Entering Reminder Data
onView(
withId(R.id.reminderTitle)
).perform(typeText("Title"))
onView(
withId(R.id.reminderDescription)
).perform(typeText("Description"))
// Setting Location from the view model
val saveReminderViewModel = get<SaveReminderViewModel>()
val poi = PointOfInterest(
LatLng(0.0, 0.0),
"fakeLocation",
"fakeLocation"
)
saveReminderViewModel.addCustomPoi(poi)
closeSoftKeyboard()
// Saving the reminder
onView(
withId(R.id.saveReminder)
).perform(click())
// Then a Toast must appear
var decorView: View? = null
activityScenario.onActivity {
decorView = it.window.decorView
}
onView(
withText(R.string.reminder_saved)
).inRoot(
withDecorView(not(decorView))
).check(matches(isDisplayed()))
}
}
|
package com.gerenciamento_escolar.api.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gerenciamento_escolar.api.repository.AlunoRepository;
import com.gerenciamento_escolar.api.repository.DisciplinaRepository;
import com.gerenciamento_escolar.api.repository.MatriculaRepository;
import com.gerenciamento_escolar.api.repository.ProfessorRepository;
import com.gerenciamento_escolar.api.service.validations.ValidacaoException;
import com.gerenciamento_escolar.api.service.validations.matricula.ValidadorMatriculaDeAlunos;
@Service
public class MatricularAluno {
@Autowired
private MatriculaRepository matriculaRepository;
@Autowired
private AlunoRepository alunoRepository;
@Autowired
private ProfessorRepository professorRepository;
@Autowired
private DisciplinaRepository disciplinaRepository;
@Autowired
private List<ValidadorMatriculaDeAlunos> validadores;
public DadosDetalhamentoMatricula matricular(DadosMatriculaAluno dados) {
System.out.println("DadosMatriculaAluno: " + dados);
if(!alunoRepository.existsById(dados.id_aluno())) {
throw new ValidacaoException(("Aluno não encontrado"));
}
if(!professorRepository.existsById(dados.id_professor())) {
throw new ValidacaoException(("Professor não encontrado"));
}
if(!disciplinaRepository.existsById(dados.id_disciplina())) {
throw new ValidacaoException(("Disciplina não encontrada"));
}
validadores.forEach(v -> v.validar(dados));
var aluno = alunoRepository.findById(dados.id_aluno()).get();
var professor = professorRepository.findById(dados.id_professor()).get();
var disciplina = disciplinaRepository.findById(dados.id_disciplina()).get();
var matriculaRealizada = new Matricula(null, aluno, professor, disciplina, dados.data(), null);
matriculaRepository.save(matriculaRealizada);
return new DadosDetalhamentoMatricula(matriculaRealizada);
}
public void cancelar(DadosCancelamentoMatricula dados) {
if (!matriculaRepository.existsById(dados.id_matricula())) {
throw new ValidacaoException("o identificador da matrícula informado não existe!");
}
var matriculaCancelada = matriculaRepository.getReferenceById(dados.id_matricula());
matriculaCancelada.cancelar(dados.motivo());
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
<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=Roboto:ital,wght@0,100;0,300;0,400;0,500;1,100;1,300;1,400;1,500&family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/shopping-cart.css">
<link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/register.css">
<title>Nike! Just do it</title>
</head>
<body class="body">
<header>
<img src="../img/logo.png" alt="Logo" style="width:100px; height:50px">
<nav class="desktop">
<ul>
<li><a href="../html/index.html">Home</a></li>
<li><a href="../html/men-category.html">Men</a></li>
<li><a href="../html/women-category.html">Women</a></li>
<li><a href="../html/shopping-cart.html">Shopping cart</a></li>
</ul>
</nav>
<div class="icons">
<i id="login" class="fa-solid fa-arrow-right-to-bracket" title="Log in"></i>
<i id="register" class="fa-solid fa-plus" title="Register"></i>
<!-- <i class="fa-solid fa-cart-plus"></i> -->
<!-- <i class="fa-solid fa-magnifying-glass"></i> -->
</div>
<div class="mobileNav">
<ul>
<li><a href="../html/index.html">Home</a></li>
<li><a href="../html/men-category.html">Men</a></li>
<li><a href="../html/women-category.html">Women</a></li>
<li><a href="../html/shopping-cart.html">Shopping cart</a></li>
</ul>
</div>
</header>
<article>
<div class="checkOut__product">
<div class="checkOut__product__shipping">
<div class="border">
<h2>Free Shipping for Members.</h2>
<p>Become a Nike Member for fast and free shipping.</p>
</div>
<h2>Bag</h2>
<div class="checkOut__product__shipping__info">
<img src="../img/men10.webp" alt="">
<div class="checkOut__product__shipping__info__quantity">
<h4>Nike Sportsweat tech Fleece</h4>
<p>Crew Sweatshirt</p>
<p>Color: Black</p>
<table>
<tr>
<th style="font-weight: 300; text-align: left; font-size: 15px;">Size</th>
<th>
<input type="text" id="txt_ide" list="ide">
<datalist id="ide">
<option value="XS"></option>
<option value="S"></option>
<option value="S Tall"></option>
<option value="M"></option>
<option value="M Tall"></option>
<option value="L"></option>
<option value="L Tall"></option>
<option value="XL"></option>
<option value="XL Tall"></option>
<option value="2XL"></option>
<option value="2XL Tall"></option>
<option value="3XL"></option>
<option value="3XL Tall"></option>
<option value="4XL"></option>
<option value="4XL Tall"></option>
</datalist>
</th>
</tr>
<tr>
<th style="font-weight: 300; text-align: left; font-size: 15px;">Quantity</th>
<th>
<input type="text" id="quantity" list="quantitys">
<datalist id="quantitys">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
<option value="4"></option>
<option value="5"></option>
<option value="6"></option>
<option value="7"></option>
<option value="8"></option>
<option value="9"></option>
<option value="10"></option>
</datalist>
</th>
</tr>
</table>
</div>
<h5 style="text-align: right; line-height: 2em">$48.97</h5>
</div>
</div>
</div>
<div class="checkOut__method">
<h2>Summary</h2>
<h3>Do you have a Promo Code?</h3>
<div class="checkOut__method__sumary">
<p>Subtotal</p>
<p>$48.97</p>
</div>
<div class="checkOut__method__sumary">
<p>Estimated Shipping & Handling</p>
<p>$8.0</p>
</div>
<div class="checkOut__method__sumary">
<p>Estimated Tax</p>
<p>-</p>
</div>
<div class="checkOut__method__sumary">
<p>Total</p>
<p id="price">$56.97</p>
</div>
</div>
<div class="Login">
<div class="login-card">
<!-- <i class="fa-solid fa-xmark"></i> -->
<h2>Login</h2>
<h3>Enter your credentials</h3>
<form action="" class="login-form">
<input type="text" id="userLogin" placeholder="Username" required>
<input type="password" id="passwordLogin" placeholder="Password" required>
<a href="#">Forget your password?</a>
<button id="submitLogin" tpye="submit" onclick="Login()">LOGIN</button>
</form>
<button id="cancelLogin">Cancel</button>
</div>
</div>
<div class="Register">
<div class="register-card">
<!-- <i class="fa-solid fa-xmark"></i> -->
<h2>Register</h2>
<h3>Enter your credentials</h3>
<form action="" class="register-form">
<input type="text" id="userRegister" placeholder="Username" required>
<input type="password" id="passwordRegister" placeholder="Password" required>
<input type="reset">
<button id="submitRegister" tpye="submit" onclick="Register()">REGISTER</button>
</form>
<button id="cancelRegister">Cancel</button>
</div>
</div>
</article>
<footer>
<p>Copyright © 2023 by Kai Vo All Rights Reserved</p>
</footer>
<script src="../js/main.js"></script>
<script src="../js/login.js"></script>
<script src="../js/register.js"></script>
<script src="../js/shopping-cart.js"></script>
</body>
</html>
|
import { Button, Container, Note } from "@tonightpass/kitchen";
import { NextPage } from "next";
import React from "react";
const NotePage: NextPage = () => {
return (
<>
<Container
gap={10}
style={{
maxWidth: 700,
margin: "0 auto",
}}
>
<p>{"sizes"}</p>
<Container row align={"flex-start"} gap={10}>
<Note size={"small"}>{"A small note."}</Note>
<Note>{"A default note."}</Note>
<Note size={"large"}>{"A large note."}</Note>
</Container>
<p>{"action"}</p>
<Container gap={10}>
<Container>
<Note
action={
<Button
size={"small"}
onClick={() => alert("i'll take note ahah")}
>
{"Upgrade\r"}
</Button>
}
>
{"This note details some information.\r"}
</Note>
</Container>
<Container>
<Note
action={
<Button
size={"small"}
onClick={() => alert("i'll take note ahah")}
>
{"Upgrade\r"}
</Button>
}
>
{"This note details a large amount information that could\r"}
{
"potentially wrap into two or more lines, forcing the height of the\r"
}
{"Note to be larger.\r"}
</Note>
</Container>
</Container>
<p>{"types"}</p>
<Container gap={10}>
<Note type={"secondary"}>
{"This note details some information."}
</Note>
<Note type={"info"}>{"info"}</Note>
<Note type={"success"}>{"success"}</Note>
<Note type={"danger"}>{"danger"}</Note>
<Note type={"warning"}>{"warning"}</Note>
</Container>
<p>{"hidden label"}</p>
<Container>
<Note label={false}>{"This note details some information."}</Note>
</Container>
<p>{"custom label"}</p>
<Container>
<Note label={"Custom"}>{"This note details some information"}</Note>
</Container>
<p>{"filled"}</p>
<Container gap={10}>
<Note fill>{"This note details something important."}</Note>
<Note fill type={"secondary"}>
{"This note details some information.\r"}
</Note>
<Note fill type={"info"}>
{"This note details an info.\r"}
</Note>
<Note fill type={"success"}>
{"This note details a success.\r"}
</Note>
<Note fill type={"danger"}>
{"This note details a danger.\r"}
</Note>
<Note fill type={"warning"}>
{"This note details a warning.\r"}
</Note>
</Container>
</Container>
</>
);
};
export default NotePage;
|
import edu.holycross.shot.chron.*
import groovy.xml.MarkupBuilder
import edu.harvard.chs.cite.CiteUrn
String contentType = "text/html"
response.setContentType(contentType)
response.setHeader( "Access-Control-Allow-Origin", "*")
String serverUrl = "@tripleserver@"
JGraph jg = new JGraph(serverUrl)
// do some error checking on this ...
String urn = params.urn
def synchronisms = jg.getSyncsForYear(urn)
String label = jg.getLabel(urn)
def pn = jg.getPrevNext(urn)
StringWriter writer = new StringWriter()
MarkupBuilder html = new MarkupBuilder(writer)
html.html {
head {
link(type : 'text/css', rel : 'stylesheet', href : 'css/chron.css', title : 'CSS stylesheet')
mkp.yield "\nINSERTSCRIPT"
title("Synchronisms for: ${label}")
}
body {
mkp.yield "\nBODYSCRIPT\n"
header {
h1 {
mkp.yield "Synchronisms with graph for: ${label}"
}
nav (role: 'navigation') {
mkp.yield "Chronometer: "
a(href: "home", "home")
mkp.yield " Filum: "
if (pn[0] != "") {
a(href : "syncyear?urn=${pn[0]}", "preceding year of ruler ")
mkp.yield ", "
}
if (pn[1] != "") {
a(href : "syncyear?urn=${pn[1]}", "next year of ruler")
}
}
}
article {
div (style : "float:right;width:40%;") {
ul {
synchronisms.each { syn ->
li {
CiteUrn year1
CiteUrn year2
try {
year1 = new CiteUrn(syn[1])
year2 = new CiteUrn(syn[3])
mkp.yield "${syn[0]} = "
String collection = year2.getCollection()
switch (collection) {
case "olympiadyear":
a (href : "olympiad?urn=${year2}" , "${syn[2]}")
break
default :
a(href : "syncyear?urn=${year2}", "${syn[2]}")
break
}
} catch (Exception e) {
mkp.yield "Count not parse identifiers for these references (${syn})"
System.err.println "synchronisms: Exception ${e}"
}
}
}
}
}
}
/*
footer {
mkp.yield "INSERTFOOTER"
}*/
}
}
String base = writer.toString()
base = base.replaceAll('INSERTSCRIPT','<script src="http://d3js.org/d3.v3.js"></script>')
String bodyScript = """
<script>
// get the data
d3.csv("syncyrcsv?urn=${urn}", function(error, links) {
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] ||
(nodes[link.source] = {name: link.source, url: link.url});
link.target = nodes[link.target] ||
(nodes[link.target] = {name: link.target, url : link.url});
link.value = +link.value;
});
var width = 500,
height = 300;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
// Set the range
var v = d3.scale.linear().range([0, 100]);
// Scale the range of the data
v.domain([0, d3.max(links, function(d) { return d.value; })]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// build the arrow.
svg.append("svg:defs").selectAll("marker")
.data(["end"]) // Different link/path types can be defined here
.enter().append("svg:marker") // This section adds in the arrows
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
// add the links and the arrows
var path = svg.append("svg:g").selectAll("path")
.data(force.links())
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", "url(#end)");
// define the nodes
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("svg:a") // Append legend elements
.attr("xlink:href",function(d) {return d.url} )
.append("g")
.attr("class", "node")
.on("click", click)
.on("dblclick", dblclick)
.call(force.drag);
// add the nodes
node.append("circle")
.attr("r", 5);
// add the text
node.append("text")
.attr("x", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
// add the curvy lines
function tick() {
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" +
d.source.x + "," +
d.source.y + "A" +
dr + "," + dr + " 0 0,1 " +
d.target.x + "," +
d.target.y;
});
node
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; });
}
// action to take on mouse click
function click() {
d3.select(this).select("text").transition()
.duration(750)
.attr("x", 22)
.style("fill", "steelblue")
.style("stroke", "lightsteelblue")
.style("stroke-width", ".5px")
.style("font", "20px sans-serif");
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 16)
.style("fill", "lightsteelblue");
}
// action to take on mouse double click
function dblclick() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 6)
.style("fill", "#ccc");
d3.select(this).select("text").transition()
.duration(750)
.attr("x", 12)
.style("stroke", "none")
.style("fill", "black")
.style("stroke", "none")
.style("font", "10px sans-serif");
}
});
</script>
"""
base = base.replaceAll('INSERTSCRIPT','<script src="http://d3js.org/d3.v3.js"></script>')
base = base.replaceAll('BODYSCRIPT', bodyScript)
println base.replaceAll('INSERTFOOTER',"""@htmlfooter@""")
|
---
aliases:
- prefix suffix
tags:
- C
date: 2023-07-25
time: 00:01
complete:
---
# Prefixos e Sufixos
> $\textit{Definição.}$ Refere-se a caracteres adicionados no início ou no final de um identificador para fins específicos
## $\text{Prefixos e Sufixos}$
| Prefixos | Significado |
|-|-|
| `0` | Valores octais |
| `0x` | Valores hexadecimais |
| **Sufixos** | |
| `U` | Tipo `unsigned` |
| `L` | Tipo `long` |
| `LL` | Tipo `long long` |
| `UL` | Tipo `unsigned long` |
| `ULL` | Tipo `unsigned long long` |
| `s` | Tipo `short` |
> [!info] Notação científica:
> - Símbolo `E+` denota $10^{+n}$.
> - Símbolo `E-` denota $10^{-n}$.
|
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {AcountListComponent} from './components/account/acount-list/acount-list.component';
import {AccountViewComponent} from './components/account/account-view/account-view.component';
import {CreateAccountComponent} from './components/account/create-account/create-account.component';
import {LoginComponent} from './components/login';
import {AuthGaurdService} from './security/helper/auth.guard';
import {ProductListComponent} from '@app/components/product/product-list/product-list.component';
import {ViewProductComponent} from '@app/components/product/view-product/view-product.component';
import {ShoppingCartComponent} from '@app/components/shopping-cart/shopping-cart.component';
import {CheckoutComponent} from '@app/components/checkout/chekout/checkout.component';
import {ThankYouComponent} from '@app/components/checkout/thank-you/thank-you.component';
import {ProductViewEmployeeComponent} from '@app/components/product/product-view-employee/product-view-employee.component';
import {CreateProductComponent} from '@app/components/product/create-product/create-product.component';
import {EditProductComponent} from '@app/components/product/edit-product/edit-product.component';
import {ProductDeletedComponent} from '@app/components/product/product-deleted/product-deleted.component';
import {CreatedComponent} from '@app/components/product/created/created.component';
import {UpdatedComponent} from '@app/components/product/updated/updated.component';
import {AccountViewEmpComponent} from '@app/components/account/account-view-emp/account-view-emp.component';
import {EditAccountEmpComponent} from '@app/components/account/edit-account-emp/edit-account-emp.component';
import {SalesReportComponent} from '@app/components/sales-report/sales-report.component';
import {CampaginListComponent} from '@app/components/campaign/campagin-list/campagin-list.component';
import {CreateCampaignComponent} from '@app/components/campaign/create-campaign/create-campaign.component';
import {EditCampaignComponent} from '@app/components/campaign/edit-campaign/edit-campaign.component';
import {AddProductToCampaignComponent} from '@app/components/campaign/add-product-to-campaign/add-product-to-campaign.component';
import {ProductListKeywordComponent} from '@app/components/product/product-list-keyword/product-list-keyword.component';
import {ProductListOutOfStockComponent} from '@app/components/product/product-list-out-of-stock/product-list-out-of-stock.component';
import {EditProductInCampaignComponent} from '@app/components/campaign/edit-product-in-campaign/edit-product-in-campaign.component';
import {SeeProductsInCampaignComponent} from '@app/components/campaign/see-products-in-campaign/see-products-in-campaign.component';
import {ProductListSaleComponent} from '@app/components/product/product-list-sale/product-list-sale.component';
import {EditAccountComponent} from '@app/components/account/edit-account/edit-account.component';
import {HomeComponentComponent} from '@app/components/home-component/home-component.component';
const routes: Routes = [
{
path: 'product-list-sale',
component: ProductListSaleComponent
},
{
path: 'sales-report/:time',
component: SalesReportComponent
},
{
path: 'see-products/:campaign',
component: SeeProductsInCampaignComponent
},
{
path: 'campaign-list',
component: CampaginListComponent
},
{
path: 'campaign-create',
component: CreateCampaignComponent
},
{
path: 'campaign-edit/:id',
component: EditCampaignComponent
},
{
path: 'product-add-to-campaign/:id',
component: AddProductToCampaignComponent
},
{
path: 'product-edit-in-campaign/:id',
component: EditProductInCampaignComponent
},
{
path: 'product-created',
component: CreatedComponent
},
{
path: 'product-updated',
component: UpdatedComponent
},
{
path: 'product-deleted',
component: ProductDeletedComponent
},
{
path: 'product-create',
component: CreateProductComponent
},
{
path: 'product-edit/:id',
component: EditProductComponent
},
{
path: 'product/:id',
component: ViewProductComponent
},
{
path: 'product-em/:id',
component: ProductViewEmployeeComponent
},
{
path: 'product-list/:category',
component: ProductListComponent
},
{
path: 'product-list-key/:keyword',
component: ProductListKeywordComponent
},
{
path: 'product-list-not-in-stock',
component: ProductListOutOfStockComponent
},
{
path: 'myCart',
component: ShoppingCartComponent,
canActivate: [AuthGaurdService]
},
{
path: 'account/account-list',
component: AcountListComponent
},
{
path: 'account-view',
component: AccountViewComponent,
canActivate: [AuthGaurdService]
},
{
path: 'account-view-emp',
component: AccountViewEmpComponent,
canActivate: [AuthGaurdService]
},
{
path: 'account-edit-emp/:username',
component: EditAccountEmpComponent,
},
{
path: 'account-edit/:username',
component: EditAccountComponent,
},
{
path: 'login',
component: LoginComponent
},
{
path: 'signup',
component: CreateAccountComponent
},
{
path: 'checkout',
component: CheckoutComponent
},
{
path: 'thankyou',
component: ThankYouComponent
},
{
path: '',
component: HomeComponentComponent
},
// otherwise redirect to home
{
path: '**',
redirectTo: '',
component: HomeComponentComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
|
#패키지 준비
from pandas import read_excel
from pandas import merge
from pandas import cut
from pandas import DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
#데이터셋 준비
df = read_excel("http://itpaper.co.kr/data/titanic.xlsx", engine='openpyxl')
df
#데이터 전처리
#결측치 확인
df.isna().sum()
#결측치 제거 -Cabin 컬럼
# Cabin 컬럼 제거
if 'Cabin' in df.columns: df.drop('Cabin', axis=1, inplace=True)
df.isna().sum()
#결측치 제거 - Embarked 컬럼 최빈값 대체
most_frequent = df['Embarked'].mode()
print(most_frequent[0])
df['Embarked'].fillna(most_frequent[0], inplace=True)
df.isna().sum()
#결측치 제거 - Age 컬럼 중앙값 대체
df['Age'].fillna(df['Age'].median(), inplace=True)
df.isna().sum()
#인덱스 설정
if 'PassengerId' in df.columns: df.set_index('PassengerId', inplace=True)
df
#컬럼 정보 확인
df.info()
#범주형 변수 타입 변환
df['Sex'] = df['Sex'].astype('category').cat.rename_categories({'male':1, 'female':0})
df['Survived'] = df['Survived'].astype('category')
df['Pclass'] = df['Pclass'].astype('category').cat.reorder_categories([1,2,3])
df['Embarked'] = df['Embarked'].astype('category').cat.rename_categories({'S':1, 'C':2, 'Q':3})
df.info()
#탐색적 데이터 분석
#데이터 요약 정보 확인
df.describe()
#생존률 시각화
plt.rcParams["font.family"] = 'NanumGothic'
plt.rcParams["font.size"] = 20
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10), dpi=100)
vc = df['Survived'].value_counts()
ax1.pie(vc, labels=vc.index, explode=[0,0.1],autopct='%1.2f%%')
ax1.set_title('Survived')
ax1.set_ylabel('')
sns.countplot(x=df['Survived'], ax=ax2)
ax2.set_title('Survived')
plt.show()
#선실의 등급별 생존률 상황
pclass_total_df = df.filter(['Pclass', 'Survived']).groupby('Pclass').count()
pclass_total_df
pclass_surv_df = df.filter(['Pclass', 'Survived']).query('Survived==1').groupby('Pclass').count()
pclass_surv_df
pclass_df = merge(pclass_total_df, pclass_surv_df, left_index=True, right_index=True)
pclass_df
pclass_df.rename(columns={'Survived_x': 'total', 'Survived_y': 'survived'}, inplace=True)
pclass_df['ratio'] = pclass_df['survived'] / pclass_df['total']
pclass_df
fig, ax = plt.subplots(1, 1, figsize=(15, 8))
sns.barplot(x=pclass_df.index, y='ratio', data=pclass_df, ax=ax)
ax.grid()
ax.set_ylabel('survived')
plt.show()
plt.close()
#연령별 분포
plt.rcParams["figure.figsize"] = (16, 8)
plt.rcParams["font.size"] = 14
sns.kdeplot(data=df, x='Age', fill=True, alpha=0.4, linewidth=0.5)
plt.grid()
plt.show()
#생존 여부에 따른 연령 분포 곡선
plt.rcParams["font.family"] = 'NanumGothic'
plt.rcParams["font.size"] = 20
f, ax = plt.subplots(1, 1, figsize=(15, 8))
# 첫 번째 그래프를 생성
sns.kdeplot(df["Age"][(df["Survived"] == 0)], ax=ax, color="Blue", shade = True)
# 첫 번째 그래프에 새로운 그래프를 덧그림
sns.kdeplot(df["Age"][(df["Survived"] == 1)], ax=ax, color="Green", shade= True)
ax.set_xlabel("Age")
ax.set_ylabel("Frequency")
ax.legend(["Not Survived","Survived"])
plt.show()
plt.rcParams["figure.figsize"] = (15, 7)
plt.rcParams["font.family"] = 'NanumGothic'
sns.scatterplot(data=df, x='Age', y='Fare', hue='Survived')
plt.grid()
plt.show()
#성별 생존률 비율
plt.rcParams["font.size"] = 16
plt.rcParams["font.family"] = 'NanumGothic'
f,ax=plt.subplots(1,2, figsize=(15, 8))
sns.countplot(x='Sex',data=df, ax=ax[0])
ax[0].set_title('탑승자 성별 비율')
sns.countplot(x='Sex',hue='Survived', data=df, ax=ax[1])
ax[1].set_title('생존여부에 따른 성별 비율')
plt.show()
plt.close()
#연령층 나누기
df['AgeCut'] = cut(df['Age'], bins=[0, 10, 20, 50, 100], include_lowest=True, labels=['baby', 'teenage', 'adult', 'old'])
df['AgeCut']
#객실, 연령층, 성별에 따른 생존률 시각화
plt.rcParams["font.size"] = 20
plt.rcParams["font.family"] = 'NanumGothic'
fig, ax = plt.subplots(1, 3, figsize=(24, 8), dpi=100)
plt.subplots_adjust(wspace=0.3)
sns.countplot(x='Pclass', hue='Survived', data=df, ax=ax[0])
sns.countplot(x='AgeCut', hue='Survived', data=df, ax=ax[1])
sns.countplot(x='Sex', hue='Survived', data=df, ax=ax[2])
plt.show()
plt.close()
#데이터셋 분할
np.random.seed(777)
# 생존 유무
df['Survived'] = df['Survived'].astype(np.float32)
# 객실 등급
df['Pclass'] = df['Pclass'].astype(np.float32)
# 성별
df['Sex'] = df['Sex'].astype(np.float32)
# 형제 혹은 부부의 수
df['SibSp'] = df['SibSp'].astype(np.float32)
# 부모 혹은 자녀의 수
df['Parch'] = df['Parch'].astype(np.float32)
# 지불한 운임
df['Fare'] = df['Fare'].astype(np.float32)
# 나이
df['Age'] = df['Age'].astype(np.float32)
# 탑승지역
df['Embarked'] = df['Embarked'].astype(np.float32)
df.info()
x_data = df.filter(['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare'], axis=1)
y_data = df.filter(['Survived'])
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=777)
x_train.info()
#모델 개발
model = Sequential()
model.add(Dense(256, input_shape=(len(x_train.columns),), activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(16, activation='relu'))
# sigmoid --> 출력 결과가 0~1 사이 값을 갖는다. => 백분율
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss = 'binary_crossentropy', metrics = ['acc'])
model.summary()
#학습하기
result = model.fit(x_train, y_train, epochs = 500, validation_data = (x_test, y_test), callbacks = [
ModelCheckpoint(filepath = 'check_point.h5', monitor = 'val_loss', verbose=1, save_best_only = True),
EarlyStopping(monitor = 'val_loss', patience=5, verbose = 1),
ReduceLROnPlateau(monitor= "val_loss", patience=3, factor = 0.5, min_lr=0.0001, verbose=1)
])
result_df = DataFrame(result.history)
result_df['epochs'] = result_df.index+1
result_df.set_index('epochs', inplace=True)
result_df
#학습 결과 평가
evaluate = model.evaluate(x_train, y_train)
print("최종 손실률: %f, 최종 정확도: %f" % (evaluate[0], evaluate[1]))
#학습 결과 시각화
# 그래프 기본 설정
# ----------------------------------------
plt.rcParams["font.family"] = 'Malgun Gothic'
plt.rcParams["font.size"] = 16
plt.rcParams['axes.unicode_minus'] = False
# 그래프를 그리기 위한 객체 생성
# ----------------------------------------
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 5), dpi=150)
# 1) 훈련 및 검증 손실 그리기
# ----------------------------------------
sns.lineplot(x=result_df.index, y='loss', data=result_df, color='blue', label='훈련 손실률', ax=ax1)
sns.lineplot(x=result_df.index, y='val_loss', data=result_df, color='orange', label='검증 손실률', ax=ax1)
ax1.set_title('훈련 및 검증 손실률')
ax1.set_xlabel('반복회차')
ax1.set_ylabel('손실률')
ax1.grid()
ax1.legend()
# 2) 훈련 및 검증 정확도 그리기
# ----------------------------------------
sns.lineplot(x=result_df.index, y='acc', data=result_df, color = 'blue', label = '훈련 정확도', ax=ax2)
sns.lineplot(x=result_df.index, y='val_acc', data=result_df, color = 'orange', label = '검증 정확도', ax=ax2)
ax2.set_title('훈련 및 검증 정확도')
ax2.set_xlabel('반복회차')
ax2.set_ylabel('정확도')
ax2.grid()
ax2.legend()
plt.show()
plt.close()
#학습 결과 적용
results = model.predict(x_test)
data_count, case_count = results.shape
print("%d개의 검증 데이터가 %d개의 경우의 수를 갖는다." % (data_count, case_count))
print(results)
f_results = results.flatten()
kdf = DataFrame({
'결과값': y_test['Survived'],
'생존확률(%)': np.round(f_results * 100, 1),
'예측치' : np.round(f_results)
})
kdf
#오차행렬
cm = confusion_matrix(kdf['결과값'], kdf['예측치'])
cmdf1 = DataFrame(cm, columns=['예측값(N)', '예측값(P)'], index=['실제값(F)', '실제값(T)'])
cmdf1
#오차행렬 히트맵
plt.rcParams["font.family"] = 'Malgun Gothic'
plt.rcParams["font.size"] = 16
plt.rcParams["figure.figsize"] = (3, 3)
# 오차 행렬을 히트맵 그래프로 표현
# -> annot : 그래프의 각 칸에 수치값 출력
# -> fmt : 수치값 출력 format (여기서는 10진수)
# -> cmap : 색상맵 (<https://matplotlib.org/3.2.1/tutorials/colors/colormaps.html>)
sns.heatmap(cm, annot = True, fmt = 'd',cmap = 'Blues')
plt.xlabel('예측값')
plt.ylabel('결과값')
plt.show()
x = (cmdf1['예측값(P)']['실제값(T)']+cmdf1['예측값(N)']['실제값(F)']) / len(y_test) * 100
print('머신러닝 분류 정확도 : %0.2f%%' % (x))
#결과 적용
dicaprio = np.array([3., 1., 19., 0., 0., 5.]).reshape(1,6)
results = model.predict(dicaprio)
results
winslet = np.array([1., 0., 17., 1., 2., 100.]).reshape(1,6)
results = model.predict(winslet)
results
leekh = np.array([2., 1., 40., 1., 0., 50.]).reshape(1,6)
results = model.predict(leekh)
results
|
using CleanArch.Application.DTOs;
using CleanArch.Application.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CleanArch.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productAppService)
{
_productService = productAppService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<ProductDto>>> Get()
{
IEnumerable<ProductDto> products = await _productService.GetProductsAsync();
if (products == null)
return NotFound("Products not found");
return Ok(products);
}
[HttpGet("{id:int}", Name = "GetProduct")]
public async Task<ActionResult<ProductDto>> Get(int id)
{
ProductDto product = await _productService.GetProductByIdAsync(id);
if (product == null)
return NotFound("Product not found");
return Ok(product);
}
[HttpPost]
public async Task<ActionResult> Post([FromBody] ProductDto productDto)
{
if (productDto == null)
return BadRequest("Invalid Data");
await _productService.CreateProductyAsync(productDto);
return new CreatedAtRouteResult("GetProduct", new { id = productDto.Id }, productDto);
}
[HttpPut("{id:int}")]
public async Task<ActionResult> Put(int id, [FromBody] ProductDto productDto)
{
if (productDto == null || productDto.Id != id)
return BadRequest();
await _productService.UpdateProductyAsync(productDto);
return Ok(productDto);
}
[HttpDelete("{id:int}")]
public async Task<ActionResult<CategoryDto>> Delete(int id)
{
ProductDto product = await _productService.GetProductByIdAsync(id);
if (product == null)
return NotFound("Product not found");
await _productService.DeleteProductyAsync(id);
return Ok(product);
}
}
}
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
import "test/tokens/FxMintTicket721/FxMintTicket721Test.t.sol";
import {Pausable} from "openzeppelin/contracts/security/Pausable.sol";
contract Unpause is FxMintTicket721Test {
function setUp() public virtual override {
super.setUp();
_createProject();
}
function test_Unpause() public {
TokenLib.pause(admin, address(fxMintTicket721));
TokenLib.unpause(admin, address(fxMintTicket721));
assertFalse(Pausable(fxMintTicket721).paused());
}
function test_RevertsWhen_UnauthorizedAccount() public {
TokenLib.pause(admin, address(fxMintTicket721));
vm.expectRevert(UNAUTHORIZED_ACCOUNT_TICKET_ERROR);
TokenLib.unpause(bob, address(fxMintTicket721));
}
function test_Unpause_RevertsWhen_NotPaused() public {
vm.expectRevert("Pausable: not paused");
TokenLib.unpause(admin, address(fxMintTicket721));
}
}
|
import { HttpClient, BasePaths } from "../../api";
import { AxiosRequestHeaders } from "axios";
export interface ICreatePurchase {
productId: string;
installments: number;
amount: number;
adressId: string;
creditCard: string;
mouth: number;
expYear: number;
cvc: number;
}
export class PurchaseApi {
public httpClient: HttpClient;
constructor() {
this.httpClient = new HttpClient(new BasePaths().getBaseurlOfPurchaseApi());
}
public async insertInWishList(productId: string, token: string) {
const response = await this.httpClient.execute.post(
`/wishlist/insert`,
{ productId: productId },
{ headers: { Authorization: `Bearer ${token}` } }
);
return response;
}
public async removeFromWishlist(productId: string, token: string) {
const response = await this.httpClient.execute.delete(`/wishlist/remove`, {
data: { productId: productId },
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
public async listWishlist(token: string) {
const response = await this.httpClient.execute.get(`/wishlist/list`, {
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
public async addProductIntoCart(productId: string, token: string) {
const response = await this.httpClient.execute.post(`/cart/insert`, {
data: { productId: productId },
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
public async getUserCart(token: string) {
const response = await this.httpClient.execute.get(`/cart/list`, {
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
public async getUserCartInDetails(token: string, pagination: number) {
const response = await this.httpClient.execute.get(
`/cart/details/${pagination}`,
{ headers: { Authorization: `Bearer ${token}` } }
);
return response;
}
public async removeFromCart(token: string, productId: string) {
const response = await this.httpClient.execute.delete(`/cart/remove`, {
data: { productId: productId },
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
public async getUserWishlistInDetails(token: string, pagination: number) {
const response = await this.httpClient.execute.get(
`/wishlist/details/${pagination}`,
{ headers: { Authorization: `Bearer ${token}` } }
);
return response;
}
public async createPurchase(body: ICreatePurchase, token?: string) {
const response = await this.httpClient.execute.post(`/insert`, body, {
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
public async updateCart(
productId: string,
newQuantie: number,
token?: string
) {
const response = await this.httpClient.execute.patch(
`/cart/patch`,
{ productId: productId, quantity: newQuantie },
{ headers: { Authorization: `Bearer ${token}` } }
);
return response;
}
public async createCart(productId: string, quantity: number, token?: string) {
const response = await this.httpClient.execute.post(
`/cart/insert`,
{ productId: productId, quantity: quantity },
{ headers: { Authorization: `Bearer ${token}` } }
);
return response;
}
public async listPurchase(pagination: number, token?: string) {
const response = await this.httpClient.execute.get(`/list/${pagination}`, {
headers: { Authorization: `Bearer ${token}` },
});
return response;
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\Category;
use App\Models\Tag;
use Illuminate\View\View;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\ProductFormRequest;
class ProductController extends Controller
{
public function load(){
if(Product::all()->count() < 5){
$filePath = __DIR__ ."/products.json";
$fileContent = file_get_contents($filePath);
$products = json_decode($fileContent, true);
foreach ($products as $key => $product) {
$imageUrls = array_map(function($imageUrl){
return "images/". $imageUrl;
}, $product["imageUrls"]);
$newProduct = new Product();
$newProduct->name = $product["name"];
$newProduct->slug = Str::slug($product["name"].' '.$key);
$newProduct->description = $product["description"];
$newProduct->moreDescription = $product["more_description"];
$newProduct->additionalInfos = $product["more_description"];
$newProduct->stock = rand(200, 600);
$newProduct->soldePrice = $product["solde_price"];
$newProduct->regularPrice = $product["regular_price"];
$newProduct->imageUrls = json_encode($imageUrls);
$newProduct->isAvailable = $product["isAvailable"];
$newProduct->isBestSeller = $product["isBestSeller"];
$newProduct->isNewArrival = $product["isNewArrival"];
$newProduct->isFeatured = $product["isFeatured"];
$newProduct->isSpecialOffer = $product["isSpecialOffer"];
$newProduct->isSpecialOffer = $product["isSpecialOffer"];
$newProduct->save();
}
return [
'result' => "created"
];
}
return [
'result' => "error"
];
}
public function index(): View
{
$products = Product::orderBy('created_at', 'desc')->paginate(5);
return view('products/index', ['products' => $products]);
}
public function show($id): View
{
$product = Product::findOrFail($id);
return view('products/show', ['product' => $product]);
}
public function create(): View
{
$categories = Category::all();
$tags = Tag::all();
return view('products/create', ['categories' => $categories, "tags"=>$tags]);
}
public function edit($id): View
{
$product = Product::findOrFail($id);
$categories = Category::all();
$tags = Tag::all();
return view('products/edit', ['product' => $product, 'categories'=> $categories, "tags"=>$tags]);
}
public function store(ProductFormRequest $req): RedirectResponse
{
$categories = $req->validated('categories');
$tags = $req->validated('tags');
$data = $req->validated();
if ($req->hasFile('imageUrls')) {
$data['imageUrls'] = json_encode($this->handleImageUpload($req->file('imageUrls')));
}
$product = Product::create($data);
$product->categories()->sync($categories);
if($tags){
$product->tags()->sync($tags);
}
return redirect()->route('admin.product.show', ['id' => $product->id]);
}
public function update(Product $product, ProductFormRequest $req)
{
$categories = $req->validated('categories');
$tags = $req->validated('tags');
$data = $req->validated();
if ($req->hasFile('imageUrls')) {
$uploadedImages = $this->handleImageUpload($req->file('imageUrls'));
// Suppression des anciennes images s'il en existe
if ($product->imageUrls && is_array($product->imageUrls)) {
foreach ($product->imageUrls as $imageUrl) {
Storage::disk('public')->delete($imageUrl);
}
}
$data['imageUrls'] = json_encode($uploadedImages);
}
$product->update($data);
$product->categories()->sync($categories);
if($tags){
$product->tags()->sync($tags);
}
return redirect()->route('admin.product.show', ['id' => $product->id]);
}
public function updateSpeed(Product $product, Request $req)
{
foreach ($req->all() as $key => $value) {
$product->update([
$key => $value
]);
}
return [
'isSuccess' => true,
'data' => $req->all()
];
}
public function delete(Product $product)
{
if ($product->imageUrls) {
foreach ($product->imageUrls as $image) {
Storage::disk('public')->delete($image);
}
}
$product->delete();
return [
'isSuccess' => true
];
}
private function handleImageUpload(\Illuminate\Http\UploadedFile|array $images): string|array
{
if (is_array($images)) {
$uploadedImages = [];
foreach ($images as $image) {
$imageName = uniqid() . '_' . $image->getClientOriginalName();
$image->storeAs('images', $imageName, 'public');
$uploadedImages[] = 'images/' . $imageName;
}
return $uploadedImages;
} else {
$imageName = uniqid() . '_' . $images->getClientOriginalName();
$images->storeAs('images', $imageName, 'public');
return 'images/' . $imageName;
}
}
}
|
/*
* Nwoke Fortune Chiemeziem
* Assagnment3 - easyStreet
*/
package model;
import java.util.Map;
/**
* @author Nwoke Fortune Chiemeziem [email protected]
* @version winter 2015
*
*/
public abstract class AbstractVehicle implements Vehicle {
/**This is the default death time of all vehicles.*/
private static final int DEFAULT_DEATH_TIME = 10;
/**This is my vehicle death time.*/
protected int myDeadTime;
/**This is the direction of my vehicle.*/
private Direction myDirection;
/**This is the x co-ordinate of my vehicle. */
private int myX;
/**This is the. */
private int myY;
/**This is my vehicle death time.*/
private final Direction myOriginalDirection;
/**This is my vehicle death time.*/
private final int myOriginalX;
/**This is my vehicle death time.*/
private final int myOriginalY;
/**This is my vehicle death time.*/
private boolean myVehicleIsAlive = true;
/**This is my vehicle death time.*/
private int myDeadWaitingTime;
/**
* This is my constructor. It initializes my instance fields.
* @param theX This is the x location of my vehicle.
* @param theY This is the Y location of my vehicle.
* @param theDirection This is the direction that my vehicle is headed.
*/
public AbstractVehicle(final int theX, final int theY, final Direction theDirection) {
myOriginalDirection = theDirection;
myOriginalX = theX;
myOriginalY = theY;
myX = myOriginalX;
myY = myOriginalY;
myDirection = myOriginalDirection;
myDeadTime = DEFAULT_DEATH_TIME;
myDeadWaitingTime = 0;
}
/**
* This is my abstract canPass method. It determines if a vehicle can pass the specified
* terrain and light.
* @param theTerrain This is the terrain of the vehicle.
* @param theLight This is the current light of the terrain of the vehicle.
* @return true if the object can pass, and false otherwise.
*/
public abstract boolean canPass(final Terrain theTerrain, final Light theLight);
/**
*
*/
@Override
public abstract Direction chooseDirection(final Map<Direction, Terrain> theNeighbors);
@Override
public void collide(final Vehicle theOther) {
if (isAlive() && theOther.isAlive()) {
if (getDeathTime() > theOther.getDeathTime()) {
myVehicleIsAlive = false;
myDeadWaitingTime = 0;
getImageFileName();
}
}
}
@Override
public int getDeathTime() {
// TODO Auto-generated method stub
return myDeadTime;
}
@Override
public abstract String getImageFileName();
@Override
public Direction getDirection() {
return myDirection;
}
@Override
public int getX() {
return myX;
}
@Override
public int getY() {
return myY;
}
@Override
public boolean isAlive() {
// TODO Auto-generated method stub
return myVehicleIsAlive;
}
@Override
public void poke() {
// if vehicle is dead.
if (!isAlive()) {
myDeadWaitingTime++;
//if dead time is up, bring it back to life
if (myDeadWaitingTime >= getDeathTime()) {
myVehicleIsAlive = true;
setDirection(Direction.random());
}
}
}
@Override
public void reset() {
myX = myOriginalX;
myY = myOriginalY;
myDirection = myOriginalDirection;
myDeadWaitingTime = 0;
myVehicleIsAlive = true;
}
@Override
public void setDirection(final Direction theDir) {
myDirection = theDir;
}
@Override
public void setX(final int theX) {
myX = theX;
}
@Override
public void setY(final int theY) {
myY = theY;
}
}
|
import {
Component,
createSignal,
For,
Signal,
Switch,
Match,
onMount,
batch,
createEffect,
onCleanup,
Setter,
} from "solid-js";
import { FileType, FILE_TYPES } from "@lib/parse";
import { addHistory, getHistory, HistoryItem } from "@lib/history";
const OpenFile: Component<{ item: HistoryItem; onclick: () => void }> = (
props
) => {
return (
<button
class={
"w-full text-md text-left p-2 pr-5 " +
"shadow-md hover:shadow-lg rounded-xl " +
"flex flex-row bg-green-50 hover:bg-green-100 "
}
onclick={() => {
props.onclick();
console.log(props.item);
}}
>
<div class="flex-1">{props.item.name}</div>
<div>{props.item.ty}</div>
</button>
);
};
const TypeSetter: Component<{ tySignal: Signal<FileType | null> }> = (
props
) => {
const [open, setOpen] = createSignal(false);
const [ty, setTy] = props.tySignal;
let mainRef: HTMLDivElement, openRef: HTMLDivElement;
const onWindowResize = () => {
if (openRef !== null) {
openRef.style.width = `${mainRef.clientWidth}px`;
}
};
onMount(() => {
window.addEventListener("resize", onWindowResize);
});
onCleanup(() => {
window.removeEventListener("resize", onWindowResize);
});
createEffect(() => {
if (open()) {
openRef.style.width = `${mainRef.clientWidth}px`;
}
});
return (
<div ref={mainRef} class="flex-1 flex flex-row">
<Switch>
<Match when={open()}>
<div ref={openRef} class="absolute">
<div
class={
"shadow-md rounded-3xl mx-2 bg-gray-100 " +
"divide-y divide-gray-200 "
}
>
<For each={FILE_TYPES}>
{(e, idx) => (
<button
class={
"text-xl text-center w-full hover:bg-gray-200 p-2 " +
(idx() === 0 ? "rounded-t-3xl " : "") +
(idx() === FILE_TYPES.length - 1 ? "rounded-b-3xl " : "")
}
onclick={() =>
batch(() => {
setOpen(false);
setTy(e);
})
}
>
{e}
</button>
)}
</For>
</div>
</div>
</Match>
<Match when={!open()}>
<button
class={
"flex-1 text-xl text-center p-2 mx-2 " +
"shadow-md rounded-3xl " +
"bg-gray-100 hover:bg-gray-200 "
}
onClick={() => {
batch(() => {
setOpen(true);
setTy(null);
});
}}
>
{!!ty() ? ty() : "Select file type"}
</button>
</Match>
</Switch>
</div>
);
};
const FILE_TYPE_STORE = "previous_fty";
const getPreviousTy = (): FileType | null =>
localStorage.getItem(FILE_TYPE_STORE) as FileType | null;
const setPreviousTy = (previous: FileType) => {
localStorage.setItem(FILE_TYPE_STORE, previous);
};
const Open: Component<{ setRoute: Setter<string> }> = (props) => {
const [ty, setTy] = createSignal<FileType | null>(null);
const [history, setHistory] = createSignal<HistoryItem[]>([]);
onMount(() => {
setTy(getPreviousTy());
setHistory(getHistory());
});
createEffect(() => {
if (ty() !== null) {
setPreviousTy(ty());
}
});
const openFile = (data: () => Promise<HistoryItem>) => {
data().then((value) => {
localStorage.setItem("cfile", JSON.stringify(value));
props.setRoute("view");
});
};
const openNewFile = (ty: FileType) => {
const fileSelector = document.createElement("input");
fileSelector.setAttribute("type", "file");
fileSelector.click();
fileSelector.onchange = (_) => {
openFile(async () => {
const file = fileSelector.files[0];
const rawdata = await file.text();
const name = file.name;
const item: HistoryItem = { rawdata, name, ty };
addHistory(item);
return item;
});
};
};
const openOldFile = (item: HistoryItem) => {
openFile(async () => {
addHistory(item);
return item;
});
};
return (
<div class="w-full h-full flex items-center justify-center bg-gray-100">
<div
class={
"w-3/5 h-4/5 bg-gray-50 rounded-3xl shadow-lg p-4 pb-2 " +
"space-y-4 flex flex-col"
}
>
<div>
<div class="text-3xl font-mono font-medium text-center">
Hysteresis.online
</div>
<div class="space-x-4 flex flex-row justify-center">
<a class="text-lg font-mono hover:text-gray-400" href="/docs">
docs
</a>
<a
class="text-lg font-mono hover:text-gray-400"
href="https://github.com/maksimil/t3conv"
>
github<3
</a>
</div>
</div>
<div class="flex flex-row">
<TypeSetter tySignal={[ty, setTy]} />
<div class="flex-1 flex flex-row">
<button
class={
"flex-1 text-xl text-center p-2 mx-2 " +
"shadow-md rounded-3xl " +
(ty() !== null
? "bg-green-50 hover:bg-green-100 hover:shadow-lg "
: "bg-gray-100 cursor-default ")
}
disabled={!ty()}
onclick={() => openNewFile(ty())}
>
Open file
</button>
</div>
</div>
<div class="flex-1 overflow-x-hidden overflow-y-auto space-y-2">
<For each={history().reverse()}>
{(item) => (
<OpenFile item={item} onclick={() => openOldFile(item)} />
)}
</For>
</div>
</div>
</div>
);
};
export default Open;
|
import { Component, EventEmitter, Input, OnInit, Output, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { ListHeaderOptions } from './list-header.model';
import { JhiEventManager } from 'ng-jhipster';
import { Subscription } from 'rxjs';
@Component({
selector: 'jhi-athma-list-header',
templateUrl: './list-header.component.html'
})
export class ListHeaderComponent implements OnInit, OnDestroy {
// @Input() pageName = '';
@Input() title = '';
@Input() createBtnTitle = '';
// To get details from parent component (here entities like role, country....) to child component
@Input() options: ListHeaderOptions;
// (notify) search click to parent Component
@Output() searchItem: EventEmitter<string> = new EventEmitter<string>();
// (notify) clear click to parent component
@Output() clearSearch: EventEmitter<string> = new EventEmitter<string>();
// (notify) export click to parent component
@Output() exportCSV: EventEmitter<string> = new EventEmitter<string>();
// (notify) new click to parent component
@Output() openNew: EventEmitter<string> = new EventEmitter<string>();
// (notify) audit click to parent component
@Output() openAudit: EventEmitter<string> = new EventEmitter<string>();
@Output() openImportDocument: EventEmitter<string> = new EventEmitter<string>();
@Output() openAdvanceSearch: EventEmitter<string> = new EventEmitter<string>();
@Output() onSelectedTabChange: EventEmitter<string> = new EventEmitter<string>();
taskMode = 'Group Task';
searchText: string;
createLink: string;
showClearSearch = false;
eventClearSubscriber: Subscription;
createPrivileges: string[];
constructor(private router: Router, private eventManager: JhiEventManager) {}
search(searchTerm) {
if (searchTerm !== undefined) {
this.searchText = searchTerm;
if (this.searchText === undefined) {
this.searchItem.emit(this.searchText);
} else if (this.searchText.trim().length === 0) {
this.searchItem.emit('*');
} else if (this.searchText.trim().length >= 3) {
this.searchItem.emit(this.convertToSpecialString(this.searchText));
}
}
}
convertToSpecialString(strData) {
let cleanStr = strData.trim();
cleanStr = cleanStr.replace(/\+/g, ' ');
cleanStr = cleanStr.replace(/ +/g, ' ');
cleanStr = cleanStr.replace(/"/g, '');
// cleanStr = cleanStr.replace(/\:/g, '\\:');
cleanStr = cleanStr.replace(/\//g, '\\/');
cleanStr = cleanStr.replace(/\[/g, '\\[');
cleanStr = cleanStr.replace(/\]/g, '\\]');
cleanStr = cleanStr.replace(/\(/g, '\\(');
cleanStr = cleanStr.replace(/\)/g, '\\)');
const splitStr = cleanStr.split(' ');
let convertStr = '';
splitStr.map(function(obj) {
// function(obj, index?)
convertStr += '*' + obj + '*' + ' ';
});
return convertStr;
}
clear() {
this.searchText = '';
this.clearSearch.emit();
this.showClearSearch = false;
}
export() {
this.exportCSV.emit(this.searchText);
}
createNew() {
if (this.options.openNew) {
this.openNew.emit('');
} else {
this.router.navigate([this.createLink], { replaceUrl: true });
}
}
ngOnInit() {
this.createLink = this.options.entityname + '-new';
if (this.options && this.options.createPrivileges) {
this.createPrivileges = this.options.createPrivileges;
}
this.eventClearSubscriber = this.eventManager.subscribe('clearSearch', (res: any) => {
if (res.content) {
this.showClearSearch = true;
} else {
this.showClearSearch = false;
}
});
}
onTabChange(index) {
this.options.selectedTabIndex = index;
this.onSelectedTabChange.emit(index);
}
audit() {
this.openAudit.emit('');
}
importDocument() {
this.openImportDocument.emit();
}
saveSearch() {
this.openAdvanceSearch.emit();
}
goToVariablePayout() {
this.router.navigate(['artha/variable-payouts/variable-payouts-new'], { replaceUrl: true });
}
// goToTemplate() {
// this.router.navigate(['artha/variable-payouts/variable-payouts-template'], { replaceUrl: true });
// }
goToTemplate() {
// const ngbModalOptions: NgbModalOptions = {
// backdrop: 'static',
// keyboard: true,
// windowClass: 'athma-modal-dialog vertical-middle-modal sm primary about-product-popup'
// };
// this.modalRef = this.modalService.open(InsertPayoutDialogComponent, ngbModalOptions);
// this.modalRef.result.then(
// result => {
// if (result) {
// }
// },
// () => {}
// );
this.router.navigate(['artha/variable-payouts/variable-payouts-template-popup'], { replaceUrl: true });
}
ngOnDestroy() {
this.eventManager.destroy(this.eventClearSubscriber);
}
}
|
/**
* __ __ __
* ____/ /_ ____/ /______ _ ___ / /_
* / __ / / ___/ __/ ___/ / __ `/ __/
* / /_/ / (__ ) / / / / / /_/ / /
* \__,_/_/____/_/ /_/ /_/\__, /_/
* / /
* \/
* http://distriqt.com
*
* @author Michael Archbold (https://github.com/marchbold)
* @created 24/2/2023
*/
package com.apm.client.commands.project
{
import com.apm.client.APM;
import com.apm.client.commands.Command;
import com.apm.client.commands.project.processes.ProjectAddProcess;
import com.apm.client.commands.project.processes.ProjectGetProcess;
import com.apm.client.commands.project.processes.ProjectSetProcess;
import com.apm.client.events.CommandEvent;
import com.apm.client.logging.Log;
import com.apm.client.processes.ProcessQueue;
import flash.events.EventDispatcher;
public class ProjectCommand extends EventDispatcher implements Command
{
// CONSTANTS
//
private static const TAG:String = "ProjectCommand";
public static const NAME:String = "project";
// VARIABLES
//
private var _parameters:Array;
// FUNCTIONALITY
//
public function ProjectCommand()
{
super();
_parameters = [];
}
public function setParameters( parameters:Array ):void
{
_parameters = parameters;
}
public function get name():String
{
return NAME;
}
public function get category():String
{
return "";
}
public function get requiresNetwork():Boolean
{
return false;
}
public function get requiresProject():Boolean
{
return true;
}
public function get description():String
{
return "controls the project parameters saved in the project definition";
}
public function get usage():String
{
return description + "\n" +
"\n" +
"apm project Prints all project parameters \n" +
"apm project get <param> Prints the project parameter value for the <param> parameter \n" +
"apm project set <param> <value> Sets a <param> project parameter to the specified <value> \n" +
"apm project set <param> Asks for input to set the value for the <param> project parameter \n" +
"apm project add <param> <value> Adds the <value> to the specified <param> project parameter array \n" +
"apm project add <param> Asks for input to add a value to the <param> project parameter array \n"
;
}
public function execute():void
{
Log.d( TAG, "execute(): [" + (_parameters.length > 0 ? _parameters.join( " " ) : " ") + "]\n" );
try
{
var queue:ProcessQueue = new ProcessQueue();
if (_parameters.length > 0)
{
var subCommand:String = _parameters[0];
switch (subCommand)
{
case "set":
{
if (_parameters.length < 2)
{
dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name ) );
dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR ) );
return;
}
queue.addProcess( new ProjectSetProcess(
_parameters.length < 2 ? null : _parameters[1],
_parameters.length < 3 ? null : _parameters.slice( 2 ).join( " " )
) );
break;
}
case "get":
{
if (_parameters.length < 2)
{
queue.addProcess( new ProjectGetProcess( null ) );
}
else
{
queue.addProcess( new ProjectGetProcess( _parameters[1] ) );
}
break;
}
case "add":
{
if (_parameters.length < 2)
{
dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name ) );
dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR ) );
return;
}
queue.addProcess( new ProjectAddProcess(
_parameters.length < 2 ? null : _parameters[1],
_parameters.length < 3 ? null : _parameters.slice( 2 ).join( " " )
) );
break;
}
default:
{
dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name ) );
dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR ) );
return;
}
}
}
else
{
// print all config
queue.addProcess( new ProjectGetProcess( null ) );
}
queue.start(
function ():void
{
dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK ) );
},
function ( error:String ):void
{
APM.io.writeError( NAME, error );
dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR ) );
}
);
}
catch (e:Error)
{
APM.io.error( e );
dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR ) );
}
}
}
}
|
import { Button } from '@material-ui/core'
import { Alert, AlertTitle } from '@mui/material'
import React from 'react'
import { Link } from 'react-router-dom'
import { authenticateUser, createUser } from '../../utils/api_calls'
import { useNavigate } from 'react-router-dom'
import {useRecoilState} from 'recoil'
import { User } from '../../recoil_utils/atoms'
type Props = {
backLink: string
buttonLabel: string,
backText: string,
data: {
first_name?: string,
last_name?: string,
username: string,
account_type?: 'doctor' | 'patient' | 'account_type',
password: string,
confirm_password?: string,
}
submissionType: string
}
const AuthFormFooter = ({ backLink, buttonLabel, backText, data, submissionType }: Props) => {
const navigate = useNavigate()
const [_, setUser] = useRecoilState(User)
const handleSubmit = async () => {
if (submissionType === 'signup') {
if (data.password != data.confirm_password) {
// todo: show an alert
alert('passwords do not match')
return
}
try{
const res = await createUser(data)
navigate("/auth/login/")
} catch (err){
alert(err)
}
}
else if (submissionType === 'login') {
const loginCredentials = {
username: data.username,
password: data.password
}
try{
const res = await authenticateUser(loginCredentials)
if (res.status === 400) {
alert('username or password is incorrect')
return
}
const user = await res.json()
setUser(user)
navigate('/')
sessionStorage.setItem('user', JSON.stringify(user))
} catch (err){
console.log("🚀 ~ file: AuthFormFooter.tsx ~ line 60 ~ handleSubmit ~ err", err)
}
}
}
return (
<div className='mt-5 d-flex justify-content-between'>
<Button
variant='contained'
color='primary'
onClick={handleSubmit}
>
{buttonLabel}
</Button>
<Link to={backLink} className='ml-4'>{backText}</Link>
</div>
)
}
export default AuthFormFooter
|
//
// VideoCaptureView.swift
// VideoOSD
//
// Created by Davorin Madaric on 27/09/2018.
// Copyright © 2018 Davorin Madaric. All rights reserved.
//
import UIKit
import AVFoundation
enum VideoCaptureError: Error {
case deviceNotFound
case inputFailed
case outputFailed
case captureSessionNotRunning
case internalError(Error)
}
class VideoCaptureView: UIView, AVCaptureFileOutputRecordingDelegate {
private let captureSession = AVCaptureSession()
private let videoFileOutput = AVCaptureMovieFileOutput()
private var previewLayer: AVCaptureVideoPreviewLayer?
private(set) var videoCaptureError: VideoCaptureError?
private var didStartRecording: ((URL) -> Void)?
private var didFinishRecording: ((URL, Error?) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
videoCaptureError = createSession()
}
private func createSession() -> VideoCaptureError? {
guard let videoCaptureDevice = AVCaptureDevice.default(for: AVMediaType.video) else {
return .deviceNotFound
}
guard let audioCaptureDevice = AVCaptureDevice.default(for: AVMediaType.audio) else {
return .deviceNotFound
}
captureSession.sessionPreset = AVCaptureSession.Preset.medium
do {
let videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
if captureSession.canAddInput(videoInput) {
captureSession.addInput(videoInput)
} else {
return .inputFailed
}
let audioInput = try AVCaptureDeviceInput(device: audioCaptureDevice)
if captureSession.canAddInput(audioInput) {
captureSession.addInput(audioInput)
} else {
return .inputFailed
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer!.frame = self.layer.bounds
previewLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.layer.addSublayer(previewLayer!)
captureSession.startRunning()
return nil
} catch let error {
return .internalError(error)
}
}
func startCapturing(to url: URL, completed: @escaping ((URL) -> Void), error: ((VideoCaptureError) -> Void)) {
guard captureSession.isRunning else {
error(.captureSessionNotRunning)
return
}
if captureSession.canAddOutput(videoFileOutput) {
captureSession.addOutput(videoFileOutput)
// Do recording and save the output to url
didStartRecording = completed
videoFileOutput.startRecording(to: url, recordingDelegate: self)
} else {
error(.outputFailed)
}
}
func stopCapturing(completed: ((URL, Error?) -> Void)?) {
didFinishRecording = completed
videoFileOutput.stopRecording()
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.sublayers?.forEach({ (subLayer) in
subLayer.frame = self.layer.bounds
})
}
// MARK: - AVCaptureFileOutputRecordingDelegate
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
didStartRecording?(fileURL)
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
didFinishRecording?(outputFileURL, error)
}
}
|
import { Image, ScrollView, StyleSheet, Text, View } from 'react-native';
import React, { useEffect, useState } from 'react';
import * as Notifications from 'expo-notifications';
import OutlineButton from '../components/ui/OutlineButton';
import { Place } from '../models/place';
import { Colors } from '../style/colors';
import { deletePlaceFromDB, fetchPlace, init } from '../utils/database';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { RootStackParamList } from '../App';
type Props = NativeStackScreenProps<RootStackParamList, 'PlaceDetails'>;
const PlaceDetails: React.FC<Props> = ({ route, navigation }) => {
const { id } = route.params;
const [place, setPlace] = useState<Place | null>(null);
const showOnMapHandler = () => {
console.log('Show on map');
navigation.navigate('Map', {
initialLocation: {
lat: place?.location?.lat || 0,
lng: place?.location?.lng || 0,
},
});
};
async function schedulePushNotification() {
await Notifications.scheduleNotificationAsync({
content: {
title: 'Warning!',
body: `You are successfuly deleted the place: ${place?.title}!`,
},
trigger: { seconds: 2 },
});
}
const deletePlace = async () => {
await deletePlaceFromDB(id);
schedulePushNotification();
navigation.navigate('AllPlaces');
};
useEffect(() => {
const loadPlace = async () => {
const place = await fetchPlace(id);
navigation.setOptions({
title: place?.title,
});
setPlace(place);
};
loadPlace();
}, []);
if (!place) {
return (
<View style={styles.fallbackContainer}>
<Text>Loading place data...</Text>
</View>
);
}
return (
<ScrollView>
{place?.imageUri && (
<Image style={styles.image} source={{ uri: place?.imageUri }} />
)}
<View style={styles.locationContainer}>
<View style={styles.addressContainer}>
<Text style={styles.address}>{place?.address}</Text>
</View>
<View style={styles.buttonContainer}>
<OutlineButton icon='map' onPress={showOnMapHandler}>
View on map
</OutlineButton>
<OutlineButton icon='trash' onPress={deletePlace}>
Delete place
</OutlineButton>
</View>
</View>
</ScrollView>
);
};
export default PlaceDetails;
const styles = StyleSheet.create({
fallbackContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
image: {
height: '35%',
minHeight: 300,
width: '100%',
},
locationContainer: {
justifyContent: 'center',
alignItems: 'center',
},
addressContainer: {
padding: 20,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '100%',
paddingHorizontal: 20,
paddingVertical: 10,
},
address: {
color: Colors.primary500,
textAlign: 'center',
fontWeight: 'bold',
fontSize: 16,
},
});
|
function [x,n] = newtonMethod(f,df, x0, tol)
% [x,n] = newtonMethod(f,df,x0,tol, itmax)
%
% Ricerca la radice di una funzione di cui è nota la derivata a partire
% da un approssimazione iniziale mediante il metodo di Newton
%
% Input:
% f: funzione di cui si ricercano le radici
% df: derivata della funzione f
% x0: approssimazione iniziale della radice
% tol: errore assoluto ammissibile
% Output:
% x: approssimazione della radice di f
% n: numero di iterazioni eseguite
if nargin ~= 4, error("Missing arguments"); end
if tol<0, error("Invalid arguments: tolerance must be non negative"); end
x = x0;
fx = feval(f,x);
dfx = feval(f,x);
x = x0- fx/dfx;
n = 1;
while abs(x-x0) > tol*( 1 + abs(x0))
x0 = x;
fx = feval(f,x0);
dfx = feval(df, x0);
if dfx==0
error("Value of derivative function is 0," + ...
"invalid first approximation");
end
n = n+1;
x = x0 - fx/dfx;
end
return
end
|
@extends('layouts.adminLayout.app')
@section('content')
<div class="content" v-cloak>
<div class="panel-header bg-primary-gradient">
<div class="page-inner py-5">
<div class="d-flex align-items-left align-items-md-center flex-column flex-md-row">
<div>
<h2 class="text-white pb-2 fw-bold"> {{ $site_name }} </h2>
<h5 class="text-white op-7 mb-2"> @lang('admin_messages.quick_summary_of_system') </h5>
</div>
@checkHostPermission('*-host_reports')
<div class="ms-md-auto py-2 py-md-0">
<a href="{{ route('admin.reports') }}" class="btn btn-primary btn-round"> @lang('admin_messages.reports') </a>
</div>
@endcheckHostPermission
</div>
</div>
</div>
<div class="page-inner mt--5" :class="{'loading' : isLoading }">
<div class="row mt--2">
<div class="col-md-6">
<div class="card full-height">
<div class="card-body">
<div class="card-title"> @lang('admin_messages.overall_statistics') </div>
<div class="card-category"> @lang('admin_messages.overall_info_about_statistics') </div>
<div class="d-flex flex-wrap justify-content-around pb-2 pt-4">
<div class="px-2 pb-2 pb-md-0 text-center">
<div id="users"></div>
<h6 class="fw-bold mt-3 mb-0"> @lang('admin_messages.total_users') </h6>
</div>
<div class="px-2 pb-2 pb-md-0 text-center">
<div id="hotels"></div>
<h6 class="fw-bold mt-3 mb-0"> @lang('admin_messages.total_hotels') </h6>
</div>
<div class="px-2 pb-2 pb-md-0 text-center">
<div id="reservations"></div>
<h6 class="fw-bold mt-3 mb-0"> @lang('admin_messages.total_reservations') </h6>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card full-height">
<div class="card-body">
<div class="card-title"> @lang('admin_messages.total_income_payout_statistics') </div>
<div class="row py-3">
<div class="col-md-4 d-flex flex-column justify-content-around">
<div>
<h6 class="fw-bold text-uppercase text-primary op-8">@lang('admin_messages.total_transactions')</h6>
<h3 class="fw-bold"> <span> @{{ dashboard_data.currency_symbol }} </span> @{{ dashboard_data.total_transactions }} </h3>
</div>
<div class="d-none">
<h6 class="fw-bold text-uppercase text-warning op-8">@lang('admin_messages.paid_out')</h6>
<h3 class="fw-bold"> <span> @{{ dashboard_data.currency_symbol }} </span> @{{ dashboard_data.paid_out }} </h3>
</div>
<div>
<h6 class="fw-bold text-uppercase text-success op-8">@lang('admin_messages.admin_earnings')</h6>
<h3 class="fw-bold"> <span> @{{ dashboard_data.currency_symbol }} </span> @{{ dashboard_data.admin_earnings }} </h3>
</div>
</div>
<div class="col-md-8">
<div id="chart-container">
<canvas id="totalIncomeChart"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-7">
<div class="card">
<div class="card-header">
<div class="card-head-row">
<div class="card-title">
@lang('admin_messages.transaction_breakdown')
</div>
<div class="card-tools">
<a href="javascript:void(0);" v-on:click="updateChartData('decrement')">
<i class="fas fa-chevron-left"></i>
</a>
<span class="mx-2"> @{{ currentYear }} </span>
<a href="javascript:void(0);" v-on:click="updateChartData('increment')">
<i class="fas fa-chevron-right"></i>
</a>
</div>
</div>
</div>
<div class="card-body">
<div id="chart-container">
<div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;"><div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div></div><div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div></div>
<canvas height="375" id="LineChart"></canvas>
</div>
</div>
</div>
</div>
<div class="col-md-5">
<div class="card">
<div class="card-header">
<div class="card-head-row card-tools-still-right">
<h4 class="card-title"> @lang('admin_messages.country_statistics') </h4>
</div>
</div>
<div class="card-body">
<div class="table-responsive table-hover" style="height: 375px;">
<table class="table">
<tbody>
<tr>
<th> @lang('admin_messages.country') </th>
<th> @lang('admin_messages.hotels') </th>
</tr>
<tr v-for="geo_data in dashboard_data.geo_data">
<td> @{{ geo_data.country_name }} </td>
<td class="fw-bold"> @{{ geo_data.hotel_count }} </td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="card full-height">
<div class="card-body">
<div class="card-title fw-mediumbold"> @lang('admin_messages.recent_users') </div>
<div class="separator-dashed"></div>
<div class="card-list">
@foreach($recent_users as $user)
<div class="item-list">
<div class="avatar">
<a href="{{ route('view_profile',['id' => $user['id']]) }}">
<img src="{{ $user['profile_picture'] }}" alt="{{ $user['name'] }}" class="avatar-img rounded-circle">
</a>
</div>
<div class="info-user ms-3">
<div class="username"> {{ $user['name'] }} </div>
<div class="status"> {{ $user['email'] }} </div>
</div>
<a href="{{ route('admin.users.edit',['id' => $user['id']]) }}" class="text-info h4">
<i class="fa fa-edit"></i>
</a>
</div>
@endforeach
</div>
</div>
</div>
</div>
<div class="col-md-8">
<div class="card full-height">
<div class="card-header">
<div class="card-head-row">
<div class="card-title"> @lang('admin_messages.recent_transactions') </div>
</div>
</div>
<div class="card-body">
@foreach($recent_transactions as $transaction)
<div class="d-flex">
<div class="avatar">
<a href="{{ route('view_profile',['id' => $transaction['user_id']]) }}">
<img src="{{ $transaction['profile_picture'] }}" alt="{{ $transaction['user_name'] }}" class="avatar-img rounded-circle">
</a>
</div>
<div class="ms-4 pt-1">
<h6 class="text-uppercase fw-bold mb-1">
<a href="{{ $transaction['link'] }}"> #{{ $transaction['link_text'] }} </a>
</h6>
<a href="{{ $transaction['link'] }}">
<span class="text-muted"> {{ $transaction['type'] }} </span>
</a>
</div>
<div class="flex-1 ms-4 ms-md-5 pt-1">
<div class="username"> {{ $transaction['payment_method'] }} </div>
<div class="status"> {{ $transaction['transaction_id'] }} </div>
</div>
<div class="float-end pt-1">
<h6 class="text-success fw-bold"> {{ $transaction['amount'] }} </h6>
</div>
</div>
@if(!$loop->last)
<div class="separator-dashed"></div>
@endif
@endforeach
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
@push('scripts')
<script type="text/javascript">
window.vueInitData = {!! json_encode([
'minYear' => global_settings('starting_year'),
'maxYear' => date('Y'),
'currentYear' => date('Y'),
'dashboard_data' => $dashboard_data,
]) !!};
</script>
@endpush
|
import { useContext, useState } from "react";
import { Link } from "react-router-dom";
import AuthContext from "../../store/auth-context";
import LoginCard from "../LoginCard/LoginCard";
import Button from "../UI/Button/Button";
import style from "./Navbar.module.scss";
function Navbar() {
const [showLoginModular, setShowLoginModular] = useState(false);
const { isLoggedIn, userName, logoutFunc } = useContext(AuthContext);
const [mobileMenuVisible, setMobileMenuVisible] = useState(false);
const loginButtonHandler = () => {
if (isLoggedIn) {
logoutFunc();
return;
}
setShowLoginModular(true);
setMobileMenuVisible(false)
};
const mobileMenuButtonHandler = () => {
setMobileMenuVisible(!mobileMenuVisible);
};
return (
<div className={style["navbar-container"]}>
{showLoginModular && <LoginCard toggleFunction={setShowLoginModular} />}
<span className={style.logo}>WESTCOAST EDUCATION</span>
<div className={style["desktop-view"]}>
<nav className={style.navbar}>
<ul>
<li>
<Link to="/">Start</Link>
</li>
<li>
<Link to="/courses">Kurser</Link>
</li>
<li>
<Link to="/teachers">Lärare</Link>
</li>
</ul>
</nav>
<div className={style["login-container"]}>
<Button
func={loginButtonHandler}
label={isLoggedIn ? "Logga ut" : "Logga in"}
background="darkBlue"
/>
{isLoggedIn && <span className={style["user-name"]}>{userName}</span>}
</div>
</div>
{mobileMenuVisible && (
<div className={style["mobile-menu-dropdown"]}>
<div className={style["dropdown-section"]}>
<Link to="/">Start</Link>
<Link to="/courses">Kurser</Link>
<Link to="/teachers">Lärare</Link>
</div>
<div className={style["dropdown-section"]}>
<p>{userName}</p>
<Button
func={loginButtonHandler}
label={isLoggedIn ? "Logga ut" : "Logga in"}
background="darkBlue"
/>
</div>
</div>
)}
<button
className={style["mobile-menu-button"]}
onClick={mobileMenuButtonHandler}
>
</button>
</div>
);
}
export default Navbar;
|
package day7
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
"golang.org/x/exp/maps"
)
type Hand struct {
Cards []string
Bet int
Type int
}
func (hand *Hand) HandType(part2 bool) int {
//Return 7: 5 of a kind
//Return 6: 4 of a kind
//Return 5: Full House
//Return 4: 3 of a kind
//Return 3: 2 pair
//Return 2: 1 pair
//return 1: High card
dict := make(map[string]int)
for _, num := range hand.Cards {
dict[num] = dict[num] + 1
}
numJs := dict["J"]
if part2 {
if numJs == 5 {
return 7
}
delete(dict, "J")
}
keys := maps.Keys(dict)
maxMapKey := keys[0]
for _, key := range keys {
if dict[key] > dict[maxMapKey] {
maxMapKey = key
}
}
if part2 {
dict[maxMapKey] += numJs
}
if len(keys) == 1 {
hand.Type = 7
return 7
} else if len(keys) == 2 {
if dict[keys[0]] == 4 || dict[keys[1]] == 4 {
hand.Type = 6
return 6
} else if (dict[keys[0]] == 3 && dict[keys[1]] == 2) || (dict[keys[0]] == 2 && dict[keys[1]] == 3) {
hand.Type = 5
return 5
}
} else if len(keys) == 3 {
if dict[keys[0]] == 3 || dict[keys[1]] == 3 || dict[keys[2]] == 3 {
hand.Type = 4
return 4
} else if (dict[keys[0]] == 2 && dict[keys[1]] == 2) || (dict[keys[0]] == 2 && dict[keys[2]] == 2) || (dict[keys[1]] == 2 && dict[keys[2]] == 2) {
hand.Type = 3
return 3
}
} else if len(keys) == 4 {
hand.Type = 2
return 2
}
hand.Type = 1
return 1
}
func evaluate(hands []Hand, part2 bool) {
sort.Slice(hands, func(i, j int) bool {
handIType := hands[i].HandType(part2)
handJType := hands[j].HandType(part2)
//A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, or 2
cardMap := map[string]string{}
if !part2 {
cardMap = map[string]string{
"A": "14",
"K": "13",
"Q": "12",
"J": "11",
"T": "10",
"9": "9",
"8": "8",
"7": "7",
"6": "6",
"5": "5",
"4": "4",
"3": "3",
"2": "2",
}
} else {
cardMap = map[string]string{
"A": "14",
"K": "13",
"Q": "12",
"T": "10",
"9": "9",
"8": "8",
"7": "7",
"6": "6",
"5": "5",
"4": "4",
"3": "3",
"2": "2",
"J": "1",
}
}
if handIType == handJType {
for index := 0; index < 5; index++ {
currentCardIString, success := cardMap[hands[i].Cards[index]]
if !success {
currentCardIString = hands[i].Cards[index]
}
currentCardI, _ := strconv.Atoi(currentCardIString)
currentCardJString, success := cardMap[hands[j].Cards[index]]
if !success {
currentCardJString = hands[j].Cards[index]
}
currentCardJ, _ := strconv.Atoi(currentCardJString)
if currentCardI == currentCardJ {
continue
} else if currentCardI < currentCardJ {
return true
}
return false
}
}
return handIType < handJType
})
totalScore := 0
for i, hand := range hands {
totalScore += hand.Bet * (i + 1)
}
fmt.Println(totalScore)
}
func Day7(fileName string) {
file, _ := os.Open(fileName)
defer file.Close()
scanner := bufio.NewScanner(file)
hands := make([]Hand, 0)
for scanner.Scan() {
currentHand := parseLine(scanner.Text())
hands = append(hands, currentHand)
}
evaluate(hands, false)
evaluate(hands, true)
}
func parseLine(line string) Hand {
lineContentsSlice := strings.Split(line, " ")
currentHand := Hand{
Cards: make([]string, 0),
Bet: 0,
}
currentBet, _ := strconv.Atoi(lineContentsSlice[1])
currentHand.Bet = currentBet
currentCards := strings.Split(lineContentsSlice[0], "")
currentHand.Cards = append(currentHand.Cards, currentCards...)
return currentHand
}
|
import React, { useState } from "react";
import { FaBars, FaTimes } from "react-icons/fa";
function Header() {
const [menuOpen, setMenuOpen] = useState(false);
const toggleMenu = () => {
setMenuOpen(!menuOpen);
};
return (
<div className="header-container">
<header className="bg-custom-green text-white flex items-center justify-between px-8 py-4">
<div className="flex items-center">
<h1 className="text-2xl font-bold tracking-wide" style={{ fontFamily: "'Comic Sans MS', cursive, sans-serif" }}>
Comment Whiz
</h1>
</div>
<nav className="absolute left-1/2 transform -translate-x-1/2 hidden md:flex space-x-8 justify-center mx-auto">
<ul className="flex space-x-8">
<li><a href="#" className="text-white hover:text-gray-300">HOME</a></li>
<li><a href="#" className="text-white hover:text-gray-300">FEATURES</a></li>
<li><a href="#" className="text-white hover:text-gray-300">ABOUT</a></li>
</ul>
</nav>
<div className="md:hidden flex items-center">
<button onClick={toggleMenu} className="text-white focus:outline-none">
{menuOpen ? <FaTimes size="24" /> : <FaBars size="24" />}
</button>
</div>
</header>
{menuOpen && (
<nav className="md:hidden bg-custom-green text-white px-4 py-2">
<ul className="space-y-4">
<li><a href="#" className="block text-white hover:text-gray-300">HOME</a></li>
<li><a href="#" className="block text-white hover:text-gray-300">FEATURES</a></li>
<li><a href="#" className="block text-white hover:text-gray-300">ABOUT</a></li>
</ul>
</nav>
)}
<div className="border-b-2 border-gray-300 mx-4"></div>
</div>
);
}
export default Header;
|
package br.com.ufc.metafit.ui
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import br.com.ufc.metafit.R
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.auth.FirebaseAuth
import com.skydoves.elasticviews.ElasticCheckButton
import io.github.muddz.styleabletoast.StyleableToast
class RecuperaActivity : AppCompatActivity() {
private lateinit var gmail: TextInputEditText
private lateinit var recuperar: ElasticCheckButton
private lateinit var correio: String
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recupera)
gmail = findViewById(R.id.gmail)
recuperar = findViewById(R.id.recuperar)
auth = FirebaseAuth.getInstance()
getRecuperar()
}
private fun getRecuperar() {
recuperar.setOnClickListener {
correio = gmail.text.toString().trim()
if (correio.isNotEmpty()) {
getEnviarCorreio()
} else {
StyleableToast.makeText(
applicationContext,
"Não se pode enviar",
Toast.LENGTH_LONG,
R.style.ColoredBackground
).show()
}
}
}
private fun getEnviarCorreio() {
auth.setLanguageCode("pt")
auth.sendPasswordResetEmail(correio).addOnCompleteListener { task ->
if (task.isSuccessful) {
StyleableToast.makeText(
applicationContext,
"Revise seu email para restaurar a senha",
Toast.LENGTH_LONG,
R.style.ColoredBackground
).show()
val i = Intent(this@RecuperaActivity, AdminActivity::class.java)
startActivity(i)
finish()
} else {
StyleableToast.makeText(
applicationContext,
"Email não cadastrado",
Toast.LENGTH_LONG,
R.style.ColoredBackground
).show()
}
}
}
}
|
package com.yy.hospital.controller;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* web请求日志切面类---专门针对控制层,如谁被请求了,花了多少时间,请求发送的参数,返回得值等
* @author yy
*/
@Aspect // 表示一个切面bean
@Component // bean容器的组件注解。虽然放在contrller包里,但它不是控制器。如果注入service,但我们又没有放在service包里
@Order(3) // 有多个日志时,ORDER可以定义切面的执行顺序(数字越大,前置越后执行,后置越前执行)
public class WebLogAspect {
//定义日志记录器--获取sl4j包下提供的logger
Logger logger = LoggerFactory.getLogger(this.getClass());
ThreadLocal<Long> startTime = new ThreadLocal<>(); //线程副本类去记录各个线程的开始时间
//定义切入点
/*1、execution 表达式主体
2、第1个* 表示返回值类型 *表示所有类型
3、包名 com.*.*.controller下
4、第4个* 类名,com.*.*.controller包下所有类
5、第5个* 方法名,com.*.*.controller包下所有类所有方法
6、(..) 表示方法参数,..表示任何参数
*/
@Pointcut("execution(public * com.*.*.controller.*.*(..))")
public void weblog() {
}
@Before("weblog()")
public void dobefore(JoinPoint joinPoint) { //方法里面注入连接点
logger.info("前置通知:"); //info ,debug ,warn ,erro四种级别,这里我们注入info级别
startTime.set(System.currentTimeMillis());
//获取servlet请求对象---因为这不是控制器,这里不能注入HttpServletRequest,但springMVC本身提供ServletRequestAttributes可以拿到
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("URL:" + request.getRequestURL().toString()); // 想那个url发的请求
logger.info("METHOD:" + request.getMethod());
logger.info("CLASS_METHOD:" + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName()); // 请求的是哪个类,哪种方法
logger.info("ARGS:" + Arrays.toString(joinPoint.getArgs())); // 方法本传了哪些参数
}
//方法的返回值注入给ret
@AfterReturning(returning = "ret", pointcut = "weblog()")
public void doafter(Object ret) {
logger.info("后置通知:");
logger.info("RESPONSE:" + ret); // 响应的内容---方法的返回值responseEntity
logger.info("SPEND:" + ( System.currentTimeMillis()-startTime.get() ));
}
}
|
import _ from 'lodash';
import logger from './logger';
import { processCapabilities, PROTOCOLS, validateCaps as validateArgs } from '@appium/base-driver';
import { fs } from '@appium/support';
const W3C_APPIUM_PREFIX = 'appium';
function inspectObject (args) {
function getValueArray (obj, indent = ' ') {
if (!_.isObject(obj)) {
return [obj];
}
let strArr = ['{'];
for (let [arg, value] of _.toPairs(obj)) {
if (!_.isObject(value)) {
strArr.push(`${indent} ${arg}: ${value}`);
} else {
value = getValueArray(value, `${indent} `);
strArr.push(`${indent} ${arg}: ${value.shift()}`);
strArr.push(...value);
}
}
strArr.push(`${indent}}`);
return strArr;
}
for (let [arg, value] of _.toPairs(args)) {
value = getValueArray(value);
logger.info(` ${arg}: ${value.shift()}`);
for (let val of value) {
logger.info(val);
}
}
}
/**
* Given a set of CLI args and the name of a driver or plugin, extract those args for that plugin
* @param {Object} extensionArgs - arguments of the form {[extName]: {[argName]: [argValue]}}
* @param {string} extensionName - the name of the extension
* @return {Object} the arg object for that extension alone
*/
function getExtensionArgs (extensionArgs, extensionName) {
if (!_.has(extensionArgs, extensionName)) {
return {};
}
if (!_.isPlainObject(extensionArgs[extensionName])) {
throw new TypeError(`Driver or plugin arguments must be plain objects`);
}
return extensionArgs[extensionName];
}
/**
* Given a set of args and a set of constraints, throw an error if any args are not mentioned in
* the set of constraints
* @param {Object} extensionArgs the args
* @param {Object} argsConstraints the constraints object
* @throws {Error} if any args were not recognized
*/
function ensureNoUnknownArgs (extensionArgs, argsConstraints) {
const knownArgNames = Object.keys(argsConstraints);
const unknownArgs = _.difference(Object.keys(extensionArgs), knownArgNames);
if (unknownArgs.length > 0) {
throw new Error(`Some arguments were not recognized: ${JSON.stringify(unknownArgs)}. ` +
`Are you sure they are in the list of supported args? ${JSON.stringify(knownArgNames)}`);
}
}
/**
* Takes in a set of driver/plugin args passed in by user, and arg constraints
* and throws an error if any arg is unknown or of the incorrect type
*
* @param {object} extensionArgs - Driver or Plugin specific args
* @param {object} argsConstraints - Constraints for arguments
* @throws {Error} if any args are not recognized or are of an invalid type
*/
function validateExtensionArgs (extensionArgs, argsConstraints) {
if (!_.isEmpty(extensionArgs) && !_.isEmpty(argsConstraints)) {
ensureNoUnknownArgs(extensionArgs, argsConstraints);
validateArgs(extensionArgs, argsConstraints);
}
}
/**
* Takes the caps that were provided in the request and translates them
* into caps that can be used by the inner drivers.
*
* @param {Object} jsonwpCapabilities
* @param {Object} w3cCapabilities
* @param {Object} constraints
* @param {Object} defaultCapabilities
*/
function parseCapsForInnerDriver (jsonwpCapabilities, w3cCapabilities, constraints = {}, defaultCapabilities = {}) {
// Check if the caller sent JSONWP caps, W3C caps, or both
const hasW3CCaps = _.isPlainObject(w3cCapabilities) &&
(_.has(w3cCapabilities, 'alwaysMatch') || _.has(w3cCapabilities, 'firstMatch'));
const hasJSONWPCaps = _.isPlainObject(jsonwpCapabilities);
let desiredCaps = {};
let processedW3CCapabilities = null;
let processedJsonwpCapabilities = null;
if (!hasW3CCaps) {
return {
protocol: PROTOCOLS.W3C,
error: new Error('W3C capabilities should be provided'),
};
}
const {W3C} = PROTOCOLS;
const protocol = W3C;
// Make sure we don't mutate the original arguments
jsonwpCapabilities = _.cloneDeep(jsonwpCapabilities);
w3cCapabilities = _.cloneDeep(w3cCapabilities);
defaultCapabilities = _.cloneDeep(defaultCapabilities);
if (!_.isEmpty(defaultCapabilities)) {
if (hasW3CCaps) {
for (const [defaultCapKey, defaultCapValue] of _.toPairs(defaultCapabilities)) {
let isCapAlreadySet = false;
// Check if the key is already present in firstMatch entries
for (const firstMatchEntry of (w3cCapabilities.firstMatch || [])) {
if (_.isPlainObject(firstMatchEntry)
&& _.has(removeAppiumPrefixes(firstMatchEntry), removeAppiumPrefix(defaultCapKey))) {
isCapAlreadySet = true;
break;
}
}
// Check if the key is already present in alwaysMatch entries
isCapAlreadySet = isCapAlreadySet || (_.isPlainObject(w3cCapabilities.alwaysMatch)
&& _.has(removeAppiumPrefixes(w3cCapabilities.alwaysMatch), removeAppiumPrefix(defaultCapKey)));
if (isCapAlreadySet) {
// Skip if the key is already present in the provided caps
continue;
}
// Only add the default capability if it is not overridden
if (_.isEmpty(w3cCapabilities.firstMatch)) {
w3cCapabilities.firstMatch = [{[defaultCapKey]: defaultCapValue}];
} else {
w3cCapabilities.firstMatch[0][defaultCapKey] = defaultCapValue;
}
}
}
if (hasJSONWPCaps) {
jsonwpCapabilities = Object.assign({}, removeAppiumPrefixes(defaultCapabilities), jsonwpCapabilities);
}
}
// Get MJSONWP caps
if (hasJSONWPCaps) {
processedJsonwpCapabilities = {...jsonwpCapabilities};
}
// Get W3C caps
if (hasW3CCaps) {
// Call the process capabilities algorithm to find matching caps on the W3C
// (see: https://github.com/jlipps/simple-wd-spec#processing-capabilities)
try {
desiredCaps = processCapabilities(w3cCapabilities, constraints, true);
} catch (error) {
logger.info(`Could not parse W3C capabilities: ${error.message}`);
return {
desiredCaps,
processedJsonwpCapabilities,
processedW3CCapabilities,
protocol,
error,
};
}
// Create a new w3c capabilities payload that contains only the matching caps in `alwaysMatch`
processedW3CCapabilities = {
alwaysMatch: {...insertAppiumPrefixes(desiredCaps)},
firstMatch: [{}],
};
}
return {desiredCaps, processedJsonwpCapabilities, processedW3CCapabilities, protocol};
}
/**
* Takes a capabilities objects and prefixes capabilities with `appium:`
* @param {Object} caps Desired capabilities object
*/
function insertAppiumPrefixes (caps) {
// Standard, non-prefixed capabilities (see https://www.w3.org/TR/webdriver/#dfn-table-of-standard-capabilities)
const STANDARD_CAPS = [
'browserName',
'browserVersion',
'platformName',
'acceptInsecureCerts',
'pageLoadStrategy',
'proxy',
'setWindowRect',
'timeouts',
'unhandledPromptBehavior'
];
let prefixedCaps = {};
for (let [name, value] of _.toPairs(caps)) {
if (STANDARD_CAPS.includes(name) || name.includes(':')) {
prefixedCaps[name] = value;
} else {
prefixedCaps[`${W3C_APPIUM_PREFIX}:${name}`] = value;
}
}
return prefixedCaps;
}
function removeAppiumPrefixes (caps) {
if (!_.isPlainObject(caps)) {
return caps;
}
const fixedCaps = {};
for (let [name, value] of _.toPairs(caps)) {
fixedCaps[removeAppiumPrefix(name)] = value;
}
return fixedCaps;
}
function removeAppiumPrefix (key) {
const prefix = `${W3C_APPIUM_PREFIX}:`;
return _.startsWith(key, prefix) ? key.substring(prefix.length) : key;
}
function getPackageVersion (pkgName) {
const pkgInfo = require(`${pkgName}/package.json`) || {};
return pkgInfo.version;
}
/**
* Pulls the initial values of Appium settings from the given capabilities argument.
* Each setting item must satisfy the following format:
* `setting[setting_name]: setting_value`
* The capabilities argument itself gets mutated, so it does not contain parsed
* settings anymore to avoid further parsing issues.
* Check
* https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/settings.md
* for more details on the available settings.
*
* @param {?Object} caps - Capabilities dictionary. It is mutated if
* one or more settings have been pulled from it
* @return {Object} - An empty dictionary if the given caps contains no
* setting items or a dictionary containing parsed Appium setting names along with
* their values.
*/
function pullSettings (caps) {
if (!_.isPlainObject(caps) || _.isEmpty(caps)) {
return {};
}
const result = {};
for (const [key, value] of _.toPairs(caps)) {
const match = /\bsettings\[(\S+)\]$/.exec(key);
if (!match) {
continue;
}
result[match[1]] = value;
delete caps[key];
}
return result;
}
const rootDir = fs.findRoot(__dirname);
export {
inspectObject, parseCapsForInnerDriver, insertAppiumPrefixes, rootDir,
getPackageVersion, pullSettings, removeAppiumPrefixes, getExtensionArgs,
validateExtensionArgs
};
|
@include('admin.layouts.header')
<style>
.lecture {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.lecture .container,
.lecturesShow {
max-width: 800px;
margin: 20px auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.lecture h1 {
text-align: center;
margin-bottom: 20px;
}
.lecture .form-group {
margin-bottom: 15px;
}
.lecture label {
display: block;
margin-bottom: 5px;
}
.lecture input[type="text"],
.lecture input[type="file"],
.lecture textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 3px;
box-sizing: border-box;
}
.lecturetextarea {
height: 150px;
}
.lecture input[type="submit"] {
background-color: #4CAF50;
color: #fff;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 3px;
}
.lecture input[type="submit"]:hover {
background-color: #45a049;
}
</style>
<div class="lecture">
<div class="container">
<h1>Add Lectures</h1>
<form id="lectureForm" action="{{ route('lecture_submit') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="hidden" name="course_id" value="{{ $course_id }}">
<div class="form-group">
<label for="title">Lecture Title:</label>
<input type="text" id="title" name="title" required>
</div>
<div class="form-group">
<label for="video">Add Video </label>
<input type="file" name="videos[]" multiple accept="video/*" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea id="description" name="description" required></textarea>
</div>
<div class="form-group">
<input type="submit" id="submitBtn" value="Add Lecture">
@if ($course->where('course_id', $course_id)->isNotEmpty())
<a href="{{ route('course_published', $course_id) }}" class="btn bg-primary text-light">Course
Published</a>
@else
<a href="#" class="btn btn-secondary text-light">Course Not Published</a>
@endif
</div>
<div id="loadingMessage" style="display: none;">
<p>Loading...</p>
<!-- You can also add a spinner icon or animation here -->
</div>
<style>
#loadingMessage {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
border-radius: 5px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
z-index: 1000;
}
</style>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
const loadingMessage = document.getElementById('loadingMessage');
const lectureForm = document.getElementById('lectureForm');
// Show loading message when form is submitted
lectureForm.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the default form submission
loadingMessage.style.display = 'block';
// Simulate form submission using fetch or AJAX
fetch(lectureForm.action, {
method: lectureForm.method,
body: new FormData(lectureForm)
})
.then(response => response.json()) // Assuming the server returns JSON response
.then(data => {
loadingMessage.style.display = 'none'; // Hide loading message
lectureForm.reset(); // Clear form fields
alert(data.message); // Display success message (replace with your own logic)
})
.catch(error => {
console.error('Error:', error);
loadingMessage.style.display = 'none'; // Hide loading message
alert(
'Error occurred. Please try again.'
); // Display error message (replace with your own logic)
});
});
});
</script>
</div>
</div>
<style>
/* Table styles */
.lecturesShow .table {
width: 100%;
border-collapse: collapse;
}
.lecturesShow .table th,
.lecturesShow .table td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
/* Table header styles */
.lecturesShow .table th {
background-color: #f2f2f2;
font-weight: bold;
color: #333;
}
/* Table row styles */
.lecturesShow .table tr {
transition: background-color 0.3s;
}
/* Hover effect for table rows */
.lecturesShow .table tr:hover {
background-color: #f9f9f9;
}
</style>
<div class="lecturesShow">
<table id="lecture-table">
<thead>
<tr>
<th>Title</th>
<th>Video</th>
</tr>
</thead>
<tbody id="lecture-list">
@foreach ($course as $key => $value)
@php
$videoPaths = json_decode($value->video);
@endphp
<tr>
<td>{{ $value->title }}</td>
<td>
@foreach ($videoPaths as $videoPath)
<video type="video/mp4" src="{{ asset($videoPath) }}" controls></video>
@endforeach
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const courseId = {{ $course_id }};
const lectureTableBody = document.getElementById('lecture-list');
// Function to load data using Fetch
function loadData(courseId) {
fetch(`/admin/lectures/${courseId}`)
.then(response => response.json())
.then(data => {
// Clear existing data
lectureTableBody.innerHTML = '';
// Append new lecture data
data.course.forEach(lecture => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${lecture.title}</td>
<td>
<video src="${lecture.video_url}" controls></video>
</td>
`;
lectureTableBody.appendChild(row);
});
// Update user name and course ID if needed
document.getElementById('user-name').textContent = data.user.name;
document.getElementById('course-id').textContent = data.course_id;
})
.catch(error => console.error('Error fetching data:', error));
}
// Call the function initially to load data for the specified course ID
loadData(courseId);
});
</script>
@include('admin.layouts.footer')
|
#include "main.h"
/**
* reverse_array - reverses content of an array of integers
* @a: pointer to an array of integers
* @n: number of elements of the array
* Return: reversed array of integers
*/
void reverse_array(int *a, int n)
{
int temp, i;
for (i = 0; i < n / 2; i++)
{
temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
}
|
package discovery
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/sirupsen/logrus"
clientv3 "go.etcd.io/etcd/client/v3"
"os"
"strings"
"time"
)
type Register struct {
EtcdAddresses []string
User string
Password string
DialTimeout int
closeCh chan struct{}
leaseID clientv3.LeaseID
keepAliveCh <-chan *clientv3.LeaseKeepAliveResponse
srvInfo Server
srvTTL int
cli *clientv3.Client
logger *logrus.Logger
}
func NewRegister(etcdAddresses []string, user, password string, logger *logrus.Logger) *Register {
return &Register{EtcdAddresses: etcdAddresses, User: user, Password: password, logger: logger, DialTimeout: 3}
}
func (r *Register) Register(serInfo Server, ttl int) (chan<- struct{}, error) {
var err error
if strings.Split(serInfo.Address, ":")[0] == "" {
return nil, errors.New("invalid ip address")
}
if r.cli, err = clientv3.New(clientv3.Config{
Endpoints: r.EtcdAddresses,
Username: r.User,
Password: r.Password,
DialTimeout: time.Duration(r.DialTimeout) * time.Second,
}); err != nil {
return nil, err
}
r.srvInfo = serInfo
r.srvTTL = ttl
if err = r.register(); err != nil {
return nil, err
}
r.closeCh = make(chan struct{})
go r.keepAlice()
return r.closeCh, nil
}
func (r *Register) register() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(r.DialTimeout)*time.Second)
defer cancel()
leaseResp, err := r.cli.Grant(ctx, int64(r.srvTTL))
if err != nil {
return err
}
r.leaseID = leaseResp.ID
if r.keepAliveCh, err = r.cli.KeepAlive(context.Background(), r.leaseID); err != nil {
return err
}
data, err := json.Marshal(r.srvInfo)
if err != nil {
return err
}
_, err = r.cli.Put(context.Background(), BuildRegisterPath(r.srvInfo), string(data), clientv3.WithLease(r.leaseID))
fmt.Println(BuildRegisterPath(r.srvInfo))
return err
}
func (r *Register) keepAlice() error {
ticker := time.NewTicker(time.Duration(r.srvTTL) * time.Second)
for {
select {
case <-r.closeCh:
if _, err := r.cli.Revoke(context.Background(), r.leaseID); err != nil {
r.logger.Fatalf("revoke failed, err: %s", err)
}
if err := r.unregister(); err != nil {
r.logger.Fatalf("unregister failed, err: %s", err)
}
os.Exit(0)
case res := <-r.keepAliveCh:
if res == nil {
if err := r.register(); err != nil {
r.logger.Warnf("register failed, err: %s", err)
}
}
case <-ticker.C:
if r.keepAliveCh == nil {
if err := r.register(); err != nil {
r.logger.Warnf("register failed, err: %s", err)
}
}
}
}
}
func (r *Register) unregister() error {
_, err := r.cli.Delete(context.Background(), BuildRegisterPath(r.srvInfo))
return err
}
|
"use client";
import { FormEvent, useState } from "react";
import { Locations, OwnerInfo, PropertyInfo, UploadImages } from "./components";
import { useMultiPageForm } from "@/hooks/useMultiPageForm";
import { Check } from "lucide-react";
import { toast } from "react-hot-toast";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEdgeStore } from "@/lib/edgestore";
type FormDataType = {
address: string;
country: string;
city: string;
latAndLng: [number, number];
rentOrSell: string;
rentPeriod: string;
title: string;
description: string;
bathRooms: string;
bedRooms: string;
price: number;
propertyType: string;
furniture: string;
surface: number;
centralizedClimat: boolean;
concierge: boolean;
parking: boolean;
storage: boolean;
pool: boolean;
downtown: boolean;
name: string;
email: string;
phoneNumber: string;
facebook: string;
instagram: string;
twitter: string;
images: string;
ownerId: string;
};
export default function page() {
const {edgestore} = useEdgeStore();
const router = useRouter();
const { data: session, status } = useSession();
if (status == "unauthenticated") {
router.push("/");
toast.error("Sign IN or Create An Account First");
}
const [enablingSubmit, setEnablingSubmit] = useState(false);
const [data, setData] = useState<FormDataType>({
address: "",
country: "",
city: "",
latAndLng: [32, -5],
title: "",
description: "",
price: 0,
rentOrSell: "sell",
rentPeriod: "Month",
propertyType: "Apartment",
bathRooms: "1",
bedRooms: "1",
furniture: "Unfurnished",
surface: 0,
centralizedClimat: false,
concierge: false,
parking: false,
storage: false,
pool: false,
downtown: false,
name: "",
email: "",
phoneNumber: "",
facebook: "",
instagram: "",
twitter: "",
images: "[]",
ownerId: (session?.user as any)?.id,
});
const { back, next, isFirstStep, isLastStep, currentStepIndex } =
useMultiPageForm(4); // currentStepIndex from 0 => currentIndex -1
function updateData(updatedData: Partial<FormDataType>) {
setData((prev) => {
return { ...prev, ...updatedData };
});
}
function handleEnblingSubmit(state: boolean) {
setEnablingSubmit(state);
}
async function onSubmit(e: FormEvent) {
console.log("your data is =>", data);
e.preventDefault();
window.scrollTo({
top: 0,
behavior: "smooth", // Adds smooth scrolling behavior
});
// So the user must upload at least 1 image
if (isLastStep && data.images == "[]") {
toast.error("Upload at least 1 image");
}
if (isLastStep) {
const imagesArray = JSON.parse(data.images)
console.log("your imagesss",imagesArray)
for (const imageURL of imagesArray) {
const res = await edgestore.myPublicImages.confirmUpload({
url: imageURL!,
});
}
try {
const res = await fetch("/api/addNewProperty", {
method: "POST",
body: JSON.stringify(data),
});
if (res.ok) {
toast.success("The announce published successfully");
router.push("/myProperties");
} else if (res.status === 400) {
// Handle bad request error
const errorMessage = await res.text();
toast.error(`Bad Request: ${errorMessage}`);
router.push("/addProperty");
} else {
// Handle other server errors
toast.error(
"Something went wrong on the server side, please try again later."
);
router.push("/addProperty");
}
} catch (error) {
// Handle network errors
toast.error(
"An error occurred while trying to connect to the server, please check your internet connection and try again."
);
router.push("/addProperty");
}
}
next();
}
return (
<form onSubmit={onSubmit} onKeyDown={(e) => {
// Prevent default form submission when Enter key is pressed
if (isLastStep && e.key === 'Enter' && enablingSubmit == false) {
e.preventDefault()
}
}}>
<div className="Container my-8 flex justify-center ">
<div
className={`${
currentStepIndex != 0 ? "max-sm:hidden" : ""
} flex flex-nowrap gap-4`}
>
<span
className={`${currentStepIndex >= 0 ? "border-blue-700 " : ""} ${
currentStepIndex >= 1 ? "bg-blue-700" : ""
} overflow-hidden border-2 rounded-full text-blue-800 flex justify-center items-center h-0 w-0 p-6`}
>
<span>
{currentStepIndex >= 1 ? (
<Check className="text-white block w-8 h-8 " />
) : (
"1"
)}
</span>
</span>
<span>
<div className="text-black font-semibold">Location</div>
<div className="text-gray-400 font-medium ">Adress</div>
</span>
</div>
<div
className={`${currentStepIndex >= 2 ? "max-sm:hidden" : ""} ${
currentStepIndex >= 1 ? "border-blue-700" : "border-gray-400"
} border-b-[3px] my-auto w-[10rem] flex justify-center h-0 font-extrabold text-xl mx-4`}
></div>
<div
className={`${
currentStepIndex != 1 ? "max-sm:hidden" : ""
} flex flex-nowrap gap-4`}
>
<span
className={`${currentStepIndex >= 1 ? "border-blue-700" : ""} ${
currentStepIndex >= 2 ? "bg-blue-700" : ""
} border-2 rounded-full text-blue-800 flex justify-center items-center h-0 w-0 p-6`}
>
<span>
{currentStepIndex >= 2 ? (
<Check className="text-white block w-8 h-8 " />
) : (
"2"
)}
</span>
</span>
<span>
<div className="text-black font-semibold">Property</div>
<div className="text-gray-400 font-medium ">Infos</div>
</span>
</div>
<div
className={`${
currentStepIndex === 0 || currentStepIndex === 3
? "max-sm:hidden"
: ""
} ${
currentStepIndex >= 2 ? "border-blue-700" : "border-gray-400"
} border-b-[3px] my-auto w-[10rem] flex justify-center h-0 font-extrabold text-xl mx-4`}
></div>
<div
className={`${
currentStepIndex != 2 ? "max-sm:hidden" : ""
} flex flex-nowrap gap-4`}
>
<span
className={`${currentStepIndex >= 2 ? "border-blue-700" : ""} ${
currentStepIndex >= 3 ? "bg-blue-700" : ""
} border-2 rounded-full text-blue-800 flex justify-center items-center h-0 w-0 p-6`}
>
<span>
{currentStepIndex >= 3 ? (
<Check className="text-white block w-8 h-8 " />
) : (
"3"
)}
</span>
</span>
<span>
<div className="text-black font-semibold">Owner</div>
<div className="text-gray-400 font-medium ">Infos</div>
</span>
</div>
<div
className={`${currentStepIndex <= 1 ? "max-sm:hidden" : ""} ${
currentStepIndex >= 3 ? "border-blue-700" : "border-gray-400"
} border-b-[3px] my-auto w-[10rem] flex justify-center h-0 font-extrabold text-xl mx-4`}
></div>
<div
className={`${
currentStepIndex != 3 ? "max-sm:hidden" : ""
} flex flex-nowrap gap-4`}
>
<span
className={`${currentStepIndex >= 3 ? "border-blue-700" : ""} ${
currentStepIndex >= 4 ? "bg-blue-700" : ""
} border-2 rounded-full text-blue-800 flex justify-center items-center h-0 w-0 p-6`}
>
<span>
{currentStepIndex == 4 ? (
<Check className="text-white block w-8 h-8 " />
) : (
"4"
)}
</span>
</span>
<span>
<div className="text-black font-semibold">Images</div>
<div className="text-gray-400 font-medium ">Upload</div>
</span>
</div>
</div>
<Locations
currentStepIndex={currentStepIndex}
{...data}
updateData={updateData}
/>
<PropertyInfo
currentStepIndex={currentStepIndex}
{...data}
updateData={updateData}
/>
<OwnerInfo
currentStepIndex={currentStepIndex}
{...data}
updateData={updateData}
/>
<UploadImages
setEnablingSubmit={handleEnblingSubmit}
currentStepIndex={currentStepIndex}
{...data}
updateData={updateData}
enablingSubmit={enablingSubmit}
/>
<div className="flex justify-center gap-4 my-12">
{!isFirstStep && (
<button
type="button"
onClick={() => {
back();
window.scrollTo({
top: 0,
behavior: "smooth", // Adds smooth scrolling behavior
});
}}
className=" bg-white text-black border border-black font-semibold px-8 py-2 rounded-md"
>
Back
</button>
)}
{(isLastStep ? enablingSubmit : true) && (
<button
type="submit"
className=" bg-blue-800 text-white font-semibold px-8 py-2 rounded-md"
>
{isLastStep ? "Publish" : "Next"}
</button>
)}
</div>
</form>
);
}
|
package app
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/CosmWasm/wasmd/x/wasm"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server/api"
srvconfig "github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/cosmos/cosmos-sdk/x/crisis"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
"github.com/gorilla/mux"
"github.com/ixofoundation/ixo-blockchain/v2/app/keepers"
"github.com/ixofoundation/ixo-blockchain/v2/app/upgrades"
v2 "github.com/ixofoundation/ixo-blockchain/v2/app/upgrades/v2"
"github.com/ixofoundation/ixo-blockchain/v2/lib/ixo"
"github.com/rakyll/statik/fs"
"github.com/spf13/cast"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
const (
appName = "IxoApp"
)
var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome = os.ExpandEnv("$HOME/.ixod")
// scheduled upgrades and forks
Upgrades = []upgrades.Upgrade{v2.Upgrade}
Forks = []upgrades.Fork{}
// If EnableSpecificWasmProposals is "", and this is "true", then enable all x/wasm proposals.
// If EnableSpecificWasmProposals is "", and this is not "true", then disable all x/wasm proposals.
WasmProposalsEnabled = "true"
// EnableSpecificWasmProposals, if set to non-empty string it must be comma-separated list of values that are all a subset
// of "EnableAllProposals" (takes precedence over WasmProposalsEnabled)
// https://github.com/CosmWasm/wasmd/blob/02a54d33ff2c064f3539ae12d75d027d9c665f05/x/wasm/internal/types/proposal.go#L28-L34
EnableSpecificWasmProposals = ""
// Verify app interface at compile time
_ simapp.App = (*IxoApp)(nil)
_ servertypes.Application = (*IxoApp)(nil)
)
// GetWasmEnabledProposals parses the WasmProposalsEnabled and
// EnableSpecificWasmProposals values to produce a list of enabled proposals to
// pass into the application.
func GetWasmEnabledProposals() []wasm.ProposalType {
if EnableSpecificWasmProposals == "" {
if WasmProposalsEnabled == "true" {
return wasm.EnableAllProposals
}
return wasm.DisableAllProposals
}
chunks := strings.Split(EnableSpecificWasmProposals, ",")
proposals, err := wasm.ConvertToProposals(chunks)
if err != nil {
panic(err)
}
return proposals
}
// Extended ABCI application
type IxoApp struct {
*baseapp.BaseApp
keepers.AppKeepers
legacyAmino *codec.LegacyAmino
appCodec codec.Codec
interfaceRegistry types.InterfaceRegistry
invCheckPeriod uint
// the module manager and configurator
mm *module.Manager
configurator module.Configurator
// simulation manager
sm *module.SimulationManager
}
// NewIxoApp returns a reference to an initialized IxoApp.
func NewIxoApp(
logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool,
homePath string, invCheckPeriod uint, appOpts servertypes.AppOptions, wasmOpts []wasm.Option,
baseAppOptions ...func(*baseapp.BaseApp),
) *IxoApp {
encodingConfig := GetEncodingConfig()
appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
wasmEnabledProposals := GetWasmEnabledProposals()
bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
app := &IxoApp{
AppKeepers: keepers.AppKeepers{},
BaseApp: bApp,
legacyAmino: legacyAmino,
appCodec: appCodec,
interfaceRegistry: interfaceRegistry,
invCheckPeriod: invCheckPeriod,
}
wasmConfig, err := wasm.ReadWasmConfig(appOpts)
// Uncomment this for debugging contracts. In the future this could be made into a param passed by the tests
// wasmConfig.ContractDebugMode = true
if err != nil {
panic(fmt.Sprintf("error while reading wasm config: %s", err))
}
app.InitKeepers(
appCodec,
bApp,
appOpts,
maccPerms,
legacyAmino,
wasmEnabledProposals,
wasmOpts,
wasmConfig,
app.BlockedAddresses(),
invCheckPeriod,
skipUpgradeHeights,
homePath,
)
app.SetupHooks()
/**** Module Options ****/
// -----------------------------------------------------
// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
// we prefer to be more strict in what arguments the modules expect.
skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants))
// NOTE: Any module instantiated in the module manager that is later modified
// must be passed by reference here.
app.mm = module.NewManager(appModules(app, encodingConfig, skipGenesisInvariants)...)
// Tell the app's module manager how to set the order of BeginBlockers, which are run at the beginning of every block.
app.mm.SetOrderBeginBlockers(orderBeginBlockers()...)
// Tell the app's module manager how to set the order of EndBlockers, which are run at the end of every block.
app.mm.SetOrderEndBlockers(orderEndBlockers()...)
// Tell the app's module manager how to set the order of InitGenesis, which are run genesis initialization.
app.mm.SetOrderInitGenesis(orderInitBlockers()...)
// TODO check if needed
ModuleBasics.RegisterInterfaces(app.interfaceRegistry)
app.mm.RegisterInvariants(&app.CrisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
// add test gRPC service for testing gRPC queries in isolation
testdata.RegisterQueryServer(app.GRPCQueryRouter(), testdata.QueryImpl{})
// setup upgrades
app.setupUpgradeHandlers()
app.setupUpgradeStoreLoaders()
// initialize stores
app.MountKVStores(app.GetKVStoreKey())
app.MountTransientStores(app.GetTransientStoreKey())
app.MountMemoryStores(app.GetMemoryStoreKey())
// initialize BaseApp
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
app.SetAnteHandler(NewIxoAnteHandler(HandlerOptions{
HandlerOptions: ante.HandlerOptions{
AccountKeeper: app.AccountKeeper,
BankKeeper: app.BankKeeper,
FeegrantKeeper: app.FeeGrantKeeper,
SignModeHandler: encodingConfig.TxConfig.SignModeHandler(),
SigGasConsumer: ixo.IxoSigVerificationGasConsumer,
},
IidKeeper: app.IidKeeper,
EntityKeeper: app.EntityKeeper,
WasmConfig: wasmConfig,
IBCKeeper: app.IBCKeeper,
TxCounterStoreKey: app.GetKey(wasm.StoreKey),
}))
// TODO add on sdk upgrade
// app.SetPostHandler(NewPostHandler(app.ProtoRevKeeper))
app.SetEndBlocker(app.EndBlocker)
// must be before Loading version
// Register snapshot extensions to enable state-sync for wasm.
if manager := app.SnapshotManager(); manager != nil {
err := manager.RegisterExtensions(
wasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.WasmKeeper),
)
if err != nil {
panic("failed to register snapshot extension: " + err.Error())
}
}
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(err.Error())
}
ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{})
// Initialize pinned codes in wasmvm as they are not persisted there
if err := app.WasmKeeper.InitializePinnedCodes(ctx); err != nil {
tmos.Exit(fmt.Sprintf("failed initialize pinned codes %s", err))
}
}
// create the simulation manager and define the order of the modules for deterministic simulations
//
// NOTE: this is not required apps that don't use the simulator for fuzz testing
// transactions
app.sm = module.NewSimulationManager(simulationModules(app, encodingConfig, skipGenesisInvariants)...)
app.sm.RegisterStoreDecoders()
return app
}
//------------------------------------------------------------------------------
// Implement `ixoapptypes.App` interface for IxoApp
//------------------------------------------------------------------------------
// Name returns the name of the App
func (app *IxoApp) Name() string { return app.BaseApp.Name() }
// GetBaseApp returns the base app of the application
func (app *IxoApp) GetBaseApp() *baseapp.BaseApp { return app.BaseApp }
// BeginBlocker application updates every begin block
func (app *IxoApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
app.beginBlockForks(ctx)
return app.mm.BeginBlock(ctx, req)
}
// EndBlocker application updates every end block
func (app *IxoApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
return app.mm.EndBlock(ctx, req)
}
// InitChainer application update at chain initialization
func (app *IxoApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
// LoadHeight loads a particular height
func (app *IxoApp) LoadHeight(height int64) error {
return app.LoadVersion(height)
}
// LegacyAmino returns IxoApp's amino codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *IxoApp) LegacyAmino() *codec.LegacyAmino {
return app.legacyAmino
}
// AppCodec returns IxoApp's app codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *IxoApp) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns IxoApp's InterfaceRegistry
func (app *IxoApp) InterfaceRegistry() types.InterfaceRegistry {
return app.interfaceRegistry
}
// SimulationManager implements the SimulationApp interface
func (app *IxoApp) SimulationManager() *module.SimulationManager {
return app.sm
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *IxoApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig srvconfig.APIConfig) {
clientCtx := apiSvr.ClientCtx
rpc.RegisterRoutes(clientCtx, apiSvr.Router)
// Register legacy tx routes.
authrest.RegisterTxRoutes(clientCtx, apiSvr.Router)
// Register new tx routes from grpc-gateway.
authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register new tendermint queries routes from grpc-gateway.
tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register legacy and grpc-gateway routes for all modules.
ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router)
ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// register swagger API from root so that other applications can override easily
if apiConfig.Swagger {
RegisterSwaggerAPI(clientCtx, apiSvr.Router)
}
}
// RegisterTxService implements the Application.RegisterTxService method.
func (app *IxoApp) RegisterTxService(clientCtx client.Context) {
authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry)
}
// RegisterTendermintService implements the Application.RegisterTendermintService method.
func (app *IxoApp) RegisterTendermintService(clientCtx client.Context) {
tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry)
}
// RegisterSwaggerAPI registers swagger route with API Server
func RegisterSwaggerAPI(ctx client.Context, rtr *mux.Router) {
statikFS, err := fs.New()
if err != nil {
panic(err)
}
staticServer := http.FileServer(statikFS)
rtr.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", staticServer))
}
// GetMaccPerms returns a copy of the module account permissions
func GetMaccPerms() map[string][]string {
dupMaccPerms := make(map[string][]string)
for k, v := range maccPerms {
dupMaccPerms[k] = v
}
return dupMaccPerms
}
//------------------------------------------------------------------------------
// Upgrades and forks
//------------------------------------------------------------------------------
// configure store loader that checks if version == upgradeHeight and applies store upgrades
func (app *IxoApp) setupUpgradeStoreLoaders() {
upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(fmt.Sprintf("failed to read upgrade info from disk: %s", err))
}
if app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
return
}
for _, upgrade := range Upgrades {
if upgradeInfo.Name == upgrade.UpgradeName {
app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &upgrade.StoreUpgrades))
}
}
}
func (app *IxoApp) setupUpgradeHandlers() {
for _, upgrade := range Upgrades {
app.UpgradeKeeper.SetUpgradeHandler(
upgrade.UpgradeName,
upgrade.CreateUpgradeHandler(app.mm, app.configurator),
)
}
}
// BeginBlockForks is intended to be ran in a chain upgrade.
func (app *IxoApp) beginBlockForks(ctx sdk.Context) {
for _, fork := range Forks {
if ctx.BlockHeight() == fork.UpgradeHeight {
fork.BeginForkLogic(ctx)
return
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.