text
stringlengths 184
4.48M
|
---|
import { useRecoilState, useResetRecoilState } from 'recoil';
import { counterAtom } from './store/atom';
export default function RecoilCounter() {
const [counter, setCounter] = useRecoilState(counterAtom);
// ↑ こうも書ける
// const counter = useRecoilValue(counterAtom);
// const setCounter = useRecoilState(counterAtom);
// 初期化
const resetCounter = useResetRecoilState(counterAtom);
const handleClick = () => {
setCounter(c => c + 1);
};
return (
<>
<button onClick={handleClick}>カウント</button>
<button onClick={resetCounter}>Reset</button>
<p>{counter}回、クリックされました。</p>
</>
);
}
|
<!doctype html>
<html>
<head>
<title>Page Title</title>
<style>
body {
margin: 0;
padding: 0;
font-family: 'Roboto', sans-serif; /* Use Roboto font */
background-image: url('assets/bg1.jpg'); /* Set your background image path */
background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed; /* Fixed background image */
}
h1 {
font-size: 2.5em; /* Set your desired font size */
font-weight: 700; /* Set your desired font weight */
color: #495057; /* Set your desired text color */
margin-top: 20px;
text-align: center;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
margin: auto;
}
/* Style the table header */
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
/* Alternate row colors in the table body */
tr:nth-child(even) {
background-color: #f2f2f2;
}
/* Style the table header background and text color */
th {
background-color: #4CAF50;
color: white;
}
/* .navbar {
background: linear-gradient(to right, #3498db, #2ecc71); */
/* You can customize the direction and colors of the gradient */
/* For example, 'to right' creates a left-to-right gradient */
/* You can use color codes or color names for the gradient stops */
/* } */
/* .navbar a { */
/* color: black ; Set the text color to contrast with the background */
/* Add additional styling for links in the navbar if needed */
/* } */
</style>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<div *ngIf="userRole=='Admin'">
<app-admin-navbar></app-admin-navbar>
</div>
<div *ngIf="userRole=='Agent'">
<app-agent-navbar></app-agent-navbar>
</div>
<div *ngIf="userRole=='Customer'">
<app-customer-navbar></app-customer-navbar>
</div>
<div *ngIf="temporaryData.getRole()=='Employee'">
<app-employee-navbar></app-employee-navbar>
</div>
<h1 >View Customer Insurance Account</h1>
<table class="table table-striped">
<thead>
<tr>
<!-- <th scope="col">Id</th> -->
<th scope="col">Customer</th>
<!-- <th scope="col">Cust LastName</th> -->
<th scope="col">Insurance Scheme</th>
<!-- <th scope="col">Insurnace Type</th> --> <!--please add -->
<!-- <th scope="col">Insurance Scheme</th> sholud be added -->
<th scope="col">Create Date</th>
<th scope="col">Maturity Date</th>
<th scope="col">Policy Term</th>
<th scope="col">Total Premium Amount</th>
<th scope="col">Profit Ratio</th>
<th scope="col">Sum Assured</th>
<th *ngIf="userRole=='Admin'" scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let account of accountData | paginate:{
id:'listing_pagination',
itemsPerPage:pageSize,
currentPage:page,
totalItems:totalRecords
};index as i">
<td>{{ getCustomerName(account.customerId)}}</td>
<td>{{getInsuranceSchemeNameFromPlanId(account.insurancePlanId)}}</td>
<td>{{ account.insuranceCreationDate}}</td>
<td>{{ account.maturityDate}}</td>
<td>{{ account.policyTerm}}</td>
<td>{{ account.totalPremium}}</td>
<td>{{ account.profitRatio}}</td>
<!-- <td>{{customer.password}}</td> -->
<td>{{account.sumAssured}}</td>
<!-- <td>{{customer.agentId}}</td> -->
<td *ngIf="userRole=='Admin'">
<button class="btn btn-primary" (click)="setId(account.id)">Edit</button>
<button class="btn btn-primary" (click)="deleteData(account.id)">Delete</button>
</td>
{{temporaryData.setCustomerInsuranceAccount(i+1)}}
</tr>
</tbody>
</table>
<div align="center">
<pagination-controls
id="listing_pagination"
[maxSize]="5"
[directionLinks]="true"
(pageChange)="page =$event"
>
</pagination-controls>
</div>
<select class="form-select" style="width: auto" (change)="changePageSize($event)">
<option [value]="5">5 items per page</option>
<option [value]="10">10 items per page</option>
<option [value]="15">15 items per page</option>
</select>
</body>
</html>
|
import React from "react";
import { Switch, Route, useLocation } from "react-router-dom";
import Users from "./features/users/Users";
import Shops from "./features/shops/Shops";
import Items from "./features/items/Items";
import SingleItemPage from "./features/items/SingleItemPage";
import LoginPage from "./features/login/LoginPage";
import NavBar from "./app/NavBar";
import AuthBox from "./features/login/AuthBox";
import PrivateRoute from "./app/PrivateRoute";
import { useSelector } from "react-redux";
import { selectLoggedInUser } from "./features/login/loginSlice";
function App() {
const currentUser = useSelector(selectLoggedInUser);
const location = useLocation();
return (
<div>
<NavBar />
{Object.keys(currentUser).length > 0 && location.pathname !== "/login" ? (
<AuthBox />
) : null}
<Switch>
<Route exact path="/login" component={LoginPage} />
<Route exact path="/items">
<PrivateRoute component={Items} />
</Route>
<Route exact path="/items/:itemId">
<PrivateRoute component={SingleItemPage} />
</Route>
<Route path="/users">
<PrivateRoute component={Users} />
</Route>
<Route path="/shops">
<PrivateRoute component={Shops} />
</Route>
</Switch>
</div>
);
}
export default App;
|
@FileAndFolderCreate
Feature: Create
In order to be able to create files
as a Warewolf user
I want a tool that creates a file at a given location
Scenario Outline: Create file at location
Given I have a destination path "<destination>" with value "<destinationLocation>"
And overwrite is "<selected>"
And destination credentials as "<username>" and "<password>"
And use private public key for destination is "<destinationPrivateKeyFile>"
And result as "<resultVar>"
And I authenticate for share at "\\SVRDEV.premier.local\FileSystemShareTestingSite" as user "SVRDEV.premier.local\Administrator" with saved password
When the create file tool is executed
Then the result variable "<resultVar>" will be "<result>"
And the execution has "<errorOccured>" error
And the debug inputs as
| File or Folder | Overwrite | Username | Password | Destination Private Key File |
| <destination> = <destinationLocation> | <selected> | <username> | String | <destinationPrivateKeyFile> |
And the debug output as
| |
| <resultVar> = <result> |
Examples:
| No | Name | destination | destinationLocation | selected | username | password | resultVar | result | errorOccured | destinationPrivateKeyFile |
| 1 | Local | [[path]] | c:\myfile.txt | True | "" | "" | [[result]] | Success | NO | |
| 2 | UNC | [[path]] | \\\\SVRDEV.premier.local\FileSystemShareTestingSite\FileCreateSharedTestingSite\test.txt | True | "" | "" | [[result]] | Success | NO | |
#TODO| 3 | UNC Secure | [[path]] | \\\\SVRDEV.premier.local\FileSystemShareTestingSite\FileCreateSharedTestingSite\Secure\test.txt | True | SVRDEV.premier.local\Administrator | Dev2@dmin123 | [[result]] | Success | NO | |
| 4 | FTP | [[path]] | ftp://SVRPDC.premier.local:1001/FORCREATEFILETESTING/test.txt | True | "" | "" | [[result]] | Success | NO | |
| 5 | FTPS | [[path]] | ftp://SVRPDC.premier.local:1002/FORCREATEFILETESTING/test.txt | True | Administrator | Dev2@dmin123 | [[result]] | Success | NO | |
| 6 | SFTP | [[path]] | sftp://SVRDEV.premier.local/test.txt | True | dev2 | Q/ulw&] | [[result]] | Success | NO | |
| 7 | SFTP | [[path]] | sftp://SVRDEV.premier.local/test1.txt | True | dev2 | Q/ulw&] | [[result]] | Success | NO | C:\\Temp\\key.opk |
Scenario Outline: Create file at location with overwrite disabled
Given I have a destination path "<destination>" with value "<destinationLocation>"
And overwrite is "<selected>"
And destination credentials as "<username>" and "<password>"
And use private public key for destination is "<destinationPrivateKeyFile>"
And result as "<resultVar>"
And I authenticate for share at "\\SVRDEV.premier.local\FileSystemShareTestingSite" as user "SVRDEV.premier.local\Administrator" with saved password
When the create file tool is executed
Then the result variable "<resultVar>" will be "<result>"
And the execution has "<errorOccured>" error
And the debug inputs as
| File or Folder | Overwrite | Username | Password | Destination Private Key File |
| <destination> = <destinationLocation> | <selected> | <username> | String | <destinationPrivateKeyFile> |
And the debug output as
| |
| <resultVar> = <result> |
Examples:
| No | Name | destination | destinationLocation | selected | username | password | resultVar | result | errorOccured | destinationPrivateKeyFile |
| 1 | Local | [[path]] | c:\myfile.txt | False | "" | "" | [[result]] | Success | NO | |
| 2 | UNC | [[path]] | \\\\SVRDEV.premier.local\FileSystemShareTestingSite\FileCreateSharedTestingSite\test.txt | False | "" | "" | [[result]] | Success | NO | |
#TODO| 3 | UNC Secure | [[path]] | \\\\SVRDEV.premier.local\FileSystemShareTestingSite\FileCreateSharedTestingSite\Secure\test.txt | False | .\Administrator | Dev2@dmin123 | [[result]] | Success | NO | |
| 4 | FTP | [[path]] | ftp://SVRPDC.premier.local:1001/FORCREATEFILETESTING/test.txt | False | "" | "" | [[result]] | Success | NO | |
| 5 | FTPS | [[path]] | ftp://SVRPDC.premier.local:1002/FORCREATEFILETESTING/test.txt | False | Administrator | Dev2@dmin123 | [[result]] | Success | NO | |
| 6 | SFTP | [[path]] | sftp://SVRDEV.premier.local/test.txt | False | dev2 | Q/ulw&] | [[result]] | Success | NO | |
| 7 | SFTP | [[path]] | sftp://SVRDEV.premier.local/test1.txt | False | dev2 | Q/ulw&] | [[result]] | Success | NO | C:\\Temp\\key.opk |
Scenario Outline: Create file at location Nulls
Given I have a destination path "<destination>" with value "<destinationLocation>"
And overwrite is "<selected>"
And destination credentials as "<username>" and "<password>"
And use private public key for destination is "<destinationPrivateKeyFile>"
And result as "<resultVar>"
When the create file tool is executed
Then the execution has "<errorOccured>" error
Examples:
| No | Name | destination | destinationLocation | selected | username | password | resultVar | result | errorOccured | destinationPrivateKeyFile |
| 1 | Local | [[path]] | NULL | True | | | [[result]] | Failure | AN | |
| 2 | Local | [[path]] | v:\myfile.txt | True | | | [[result]] | Failure | AN | |
| 3 | SFTP | [[path]] | sftp://SVRDEV.premier.local/test1.txt | True | "" | Q/ulw&] | [[result]] | Failure | AN | C:\\Temp\ |
#TODO| 5 | UNC Secure | [[path]] | \\\\SVRDEV.premier.local\FileSystemShareTestingSite\FileCreateSharedTestingSite\Secure\test.tx | True | dev2.local\Administrator | Dev2@dmin123 | [[result]] | Failure | AN | |
Scenario Outline: Create file at location with invalid directories
Given I have a destination path "<destination>" with value "<destinationLocation>"
And overwrite is "<selected>"
And destination credentials as "<username>" and "<password>"
And result as "<resultVar>"
When the create file tool is executed
Then the result variable "<resultVar>" will be "<result>"
And the execution has "<errorOccured>" error
And the debug inputs as
| File or Folder | Overwrite | Username | Password |
| <destination> = <destinationLocation> | <selected> | <username> | String |
And the debug output as
| |
| <resultVar> = <result> |
Examples:
| No | Name | destination | destinationLocation | selected | username | password | resultVar | result | errorOccured |
| 1 | Local | [[variable]] | "" | False | dev2 | Q/ulw&] | [[result]] | | AN |
| 2 | Local | [[var]] | | False | dev2 | Q/ulw&] | [[result]] | | AN |
| 3 | Local | 8751 | 8751 | False | dev2 | Q/ulw&] | [[result]] | | AN |
|
<section class="flex center h-100">
<form [formGroup]="formGroup" class="w-300px">
<mat-toolbar class="toolbar" color="primary">Anmelden</mat-toolbar>
<mat-card class="flex between wrap">
<mat-form-field class="form-field w-100">
<input type="text" matInput placeholder="E-Mail-Adresse" formControlName="email">
</mat-form-field>
<div *ngIf="email.invalid && (email.dirty || email.touched)"
class="alert">
<div *ngIf="email.errors?.['required']" class="form-field error">
E-Mail ist verpflichtend
</div>
<div *ngIf="email.errors?.['email']" class="form-field error">
Es muss eine valide E-Mail-Adresse sein
</div>
</div>
<mat-form-field class="form-field w-100">
<input type="password" matInput placeholder="Passwort" formControlName="password">
</mat-form-field>
<div *ngIf="password.invalid && (password.dirty || password.touched)"
class="alert">
<div *ngIf="password.errors?.['required']" class="form-field error">
Passwort ist verpflichtend
</div>
</div>
<div *ngIf="showRetype">
<mat-form-field class="form-field w-100">
<input autofocus type="password" matInput placeholder="Passwort wiederholen" formControlName="retypePassword">
</mat-form-field>
</div>
<div *ngIf="showChangePassword">
<mat-form-field class="form-field w-100">
<input autofocus type="password" matInput placeholder="Neues Passwort" formControlName="newPassword">
</mat-form-field>
<mat-form-field class="form-field w-100">
<input autofocus type="password" matInput placeholder="Neues Passwort wiederholen" formControlName="retypeNewPassword">
</mat-form-field>
</div>
<button mat-flat-button class="blue-text" (click)="onRegister()">Noch keinen Account?</button>
<button mat-raised-button color="primary" (click)="onLogin()">Anmelden</button>
<div *ngIf="errorMessage != ''" class="form-field error">{{ errorMessage }}</div>
</mat-card>
</form>
</section>
|
import { useState } from "react";
import { Link, withRouter } from "react-router-dom";
import { ReactComponent as Logo } from "../assets/images/logo.svg";
function Header({ onLight, location }) {
const [ToggleMenu, setToggleMenu] = useState(false);
const linkColor = onLight ? "text-white sm:text-gray-900" : "text-white";
const linkCTA =
location.pathname.indexOf("/login") > -1 ? `/register` : `/login`;
const textCTA =
location.pathname.indexOf("/login") > -1 ? "Register" : "Login";
const classNameLogo = onLight
? ToggleMenu
? "on-dark"
: "on-light"
: "on-dark";
return (
<header
className={[
"flex justify-between items-center",
ToggleMenu ? "fixed w-full px-4 -ml-4" : "",
].join(" ")}
>
<div style={{ height: 54 }} className="z-50">
<Logo className={{ classNameLogo }} />
</div>
<div className="flex sm:hidden ">
<button
onClick={() => setToggleMenu((prev) => !prev)}
className={["toggle z-50", ToggleMenu ? "active" : ""].join(" ")}
/>
</div>
<ul
className={[
"transition-all duration-200 items-center fixed inset-0 bg-indigo-900 pt-24 md:pt-0 md:bg-transparent md:relative md:flex md:opacity-100 md:visible",
ToggleMenu ? "opacity-100 visible z-20" : "opacity-0 invisible",
].join(" ")}
>
<li className="my-4 md:my-0">
<a
href={`${process.env.REACT_APP_FRONTPAGE_URL}/`}
className={[
linkColor,
"text-white hover:text-blue-500 text-lg px-6 py-3 my-4 sm:my-0 font-medium",
].join(" ")}
>
Home
</a>
</li>
<li className="my-4 md:my-0">
<a
href={`${process.env.REACT_APP_FRONTPAGE_URL}/courses`}
className={[
linkColor,
"text-white hover:text-blue-500 text-lg px-6 py-3 my-4 sm:my-0 font-medium",
].join(" ")}
>
Explore
</a>
</li>
<li className="my-4 md:my-0">
<a
href={`${process.env.REACT_APP_FRONTPAGE_URL}/`}
className={[
linkColor,
"text-white hover:text-blue-500 text-lg px-6 py-3 my-4 sm:my-0 font-medium",
].join(" ")}
>
Features
</a>
</li>
<li className="my-4 md:my-0">
<a
href={`${process.env.REACT_APP_FRONTPAGE_URL}/`}
className={[
linkColor,
"text-white hover:text-blue-500 text-lg px-6 py-3 my-4 sm:my-0 font-medium",
].join(" ")}
>
Blog
</a>
</li>
<li className="mt-8 md:mt-0">
<Link
to={linkCTA}
className="bg-indigo-700 hover:bg-indigo-900 text-white text-lg transition-all duration-200 px-6 py-3 my-4 sm:my-0 font-medium ml-6"
>
{textCTA}
</Link>
</li>
</ul>
</header>
);
}
export default withRouter(Header);
|
/**
* Deck objects represent a deck of playing cards.
*
* @author Kevin Nash (kjn33)
* @version 2015.4.26
*/
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
public class Deck extends ArrayList<Card> {
/** The face values represented by the cards in this Deck **/
private Card.Face[] faces;
/** The suits represented by the cards in this Deck **/
private Card.Suit[] suits;
/** The unique suits represented by the cards in this Deck **/
private Card.Suit[] uniqueSuits;
/**
* Constructs a typical Deck
*/
public Deck() {
this(Card.Face.ACE, Card.Face.KING, Card.Suit.SPADES, Card.Suit.HEARTS, Card.Suit.DIAMONDS, Card.Suit.CLUBS);
}
/**
* Constructs a custom Deck
* @param minFace the minimum face value
* @param maxFace the maximum face value
* @param suits the possible Suits for each Card
*/
public Deck(Card.Face minFace, Card.Face maxFace, Card.Suit... suits) {
// define the face values to be used
this.faces = new Card.Face[maxFace.ordinal() - minFace.ordinal() + 1];
Card.Face[] allFaces = Card.Face.values();
for (int i = 0; i < this.faces.length; i++)
this.faces[i] = allFaces[i + minFace.ordinal()];
// define the suits to be used
this.suits = suits;
// copy suits data into a HashSet to remove duplicate suits, measure new size
List<Card.Suit> auxList = Arrays.asList(suits);
TreeSet<Card.Suit> auxSet = new TreeSet<Card.Suit>(auxList);
uniqueSuits = new Card.Suit[auxSet.size()];
int auxIndex = 0;
// add all suits in auxSet to uniqueSuits
for (Card.Suit suit : auxSet)
uniqueSuits[auxIndex++] = suit;
// add to the deck one of every face/suit combination
for (Card.Face face : faces) {
for (Card.Suit suit : suits)
this.add(new Card(face, suit));
}
}
/**
* Returns the number of unique Suits in this Deck
* @return number of unique suits
*/
public int getNumberSuits() {
return uniqueSuits.length;
}
/**
* Returns the Suits in this Deck
* @return suits
*/
public Card.Suit[] getUniqueSuits() {
return uniqueSuits;
}
/**
* Returns the minimum face value used in this deck
* @return minimum face value
*/
public Card.Face getMinFace() {
return this.faces[0];
}
/**
* Returns the maximum face value used in this deck
* @return maximum face value
*/
public Card.Face getMaxFace() {
return this.faces[faces.length - 1];
}
/**
* Shuffles this Deck
*/
public void shuffle() {
Collections.shuffle(this);
}
/**
* Returns the top Card on the deck
* @return Card
*/
public Card drawCard() {
Card drawnCard = this.get(this.size() - 1);
this.remove(this.size() - 1);
return drawnCard;
}
/**
* Places the input Card at the bottom of the deck
* @param Card
*/
public void insertCard(Card card) {
this.add(0, card);
}
/**
* Returns a String representation of this Deck
* @return String version of Deck
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// Interate over each card
for (int i = 0; i < this.size() - 1; i++) {
sb.append(this.get(i).toString());
sb.append(((i + 1) % uniqueSuits.length == 0) ? "\n" : " ");
}
sb.append(this.get(this.size() - 1).toString());
return sb.toString();
}
/**
* Flips Cards so that none are face up
*/
public void hideCards() {
// Iterate over each Card
for (Card card : this) {
card.setIsFaceUp(false);
}
}
/**
* Flips Cards so that all are face up
*/
public void showCards() {
// Iterate over each Card
for (Card card : this) {
card.setIsFaceUp(true);
}
}
}
|
CREATE TABLE IF NOT EXISTS customer (
"id" varchar PRIMARY KEY,
"first_name" varchar(128),
"last_name" varchar(128),
"segment" varchar(128)
);
CREATE TABLE IF NOT EXISTS address (
"id" integer PRIMARY KEY,
"country" varchar(128),
"region" varchar(128),
"state" varchar(128),
"city" varchar(128),
"postal_code" integer
);
CREATE TABLE IF NOT EXISTS resident (
"customer_id" varchar(16),
"address_id" integer,
PRIMARY KEY ("customer_id", "address_id"),
FOREIGN KEY ("customer_id") REFERENCES "customer" ("id"),
FOREIGN KEY ("address_id") REFERENCES "address" ("id")
);
CREATE TABLE IF NOT EXISTS product (
"id" varchar(16) PRIMARY KEY,
"name" text,
"cost" float,
"sell_price" float,
"category" varchar(128),
"sub_category" varchar(128)
);
CREATE TABLE IF NOT EXISTS orders (
"id" varchar(32) PRIMARY KEY,
"order_date" date,
"customer_id" varchar(16),
FOREIGN KEY ("customer_id") REFERENCES "customer" ("id")
);
CREATE TABLE IF NOT EXISTS shipment (
"id" varchar(64) PRIMARY KEY,
"ship_mode" varchar(64),
"address_id" integer,
"ship_date" date,
FOREIGN KEY ("address_id") REFERENCES "address" ("id")
);
CREATE TABLE IF NOT EXISTS orderitems (
"product_id" varchar(16),
"order_id" varchar(32),
"discount" float,
"quantity" integer,
"shipment_id" varchar(64),
PRIMARY KEY ("product_id", "order_id"),
FOREIGN KEY ("product_id") REFERENCES "product" ("id"),
FOREIGN KEY ("order_id") REFERENCES "orders" ("id"),
FOREIGN KEY ("shipment_id") REFERENCES "shipment" ("id")
);
-- 1. What is the category generating the maximum sales revenue?
-- What about the profit in this category?
-- Are they making a loss in any categories?
SELECT p.category, SUM(p.sell_price *(1 - oi.discount) * oi.quantity)::numeric(30,2) as sales,
SUM(p.sell_price *(1 - oi.discount) * oi.quantity - oi.quantity * p.cost)::numeric(30,2) as profit
FROM Product p
JOIN OrderItems oi ON p.id = oi.product_id
JOIN Orders o ON o.id = oi.order_id
GROUP BY p.category
ORDER BY sales DESC
SELECT *
FROM(
SELECT p.name, p.category,
SUM(p.sell_price *(1 - oi.discount) * oi.quantity - oi.quantity * p.cost)::numeric(30,2) as profit
FROM Product p
JOIN OrderItems oi ON p.id = oi.product_id
JOIN Orders o ON o.id = oi.order_id
GROUP BY p.name, p.category)
WHERE profit < 0
ORDER BY profit
--2. What are 5 states generating the maximum and minimum sales revenue?
CREATE TEMPORARY TABLE StateRevenue AS
SELECT a.state,
SUM(p.sell_price *(1 - oi.discount) * oi.quantity)::numeric(30,2) as sales
FROM Product p
JOIN OrderItems oi ON p.id = oi.product_id
JOIN Shipment s ON oi.shipment_id = s.id
JOIN Address a ON a.id = s.address_id
GROUP BY a.state
ORDER BY sales;
--Maximum
SELECT state
FROM StateRevenue
ORDER BY sales DESC
LIMIT 5;
--Minimum
SELECT state
FROM StateRevenue
ORDER BY sales
LIMIT 5;
-- 3. What are the 3 products in each product segment with the highest sales?
-- Are they the 3 most profitable products as well?
SELECT *
FROM(
SELECT *,
RANK () OVER (PARTITION BY pq.segment ORDER BY pq.sales DESC) AS s_rank,
RANK () OVER (PARTITION BY pq.segment ORDER BY pq.profit DESC) AS p_rank
FROM(
SELECT p.id, p.name, c.segment,
SUM(p.sell_price *(1 - oi.discount) * oi.quantity)::numeric(30,2) as sales,
SUM(p.sell_price *(1 - oi.discount) * oi.quantity - oi.quantity * p.cost)::numeric(30,2) as profit
FROM Product p
JOIN OrderItems oi ON p.id = oi.product_id
JOIN Orders o ON o.id = oi.order_id
JOIN Customer c ON c.id= o.customer_id
GROUP BY p.id, p.name, c.segment) pq) pr
WHERE s_rank <= 3
ORDER BY segment, s_rank
-- 4. What are the 3 best-seller products in each product segment? (Quantity-wise)
SELECT *
FROM(
SELECT *,
RANK () OVER (PARTITION BY pq.segment ORDER BY pq.total_quantity DESC) AS q_rank
FROM(
SELECT p.id, p.name, c.segment,
SUM(oi.quantity) as total_quantity
FROM Product p
JOIN OrderItems oi ON p.id = oi.product_id
JOIN Orders o ON o.id = oi.order_id
JOIN Customer c ON c.id= o.customer_id
GROUP BY p.id, p.name, c.segment) pq) pr
WHERE q_rank <= 3
ORDER BY segment, q_rank
-- 5. What are the top 3 worst-selling products in every category? (Quantity-wise)
SELECT *
FROM(
SELECT qt.id, qt.name, p.category, qt.total_quantity,
RANK () OVER (PARTITION BY category ORDER BY total_quantity ASC) AS q_rank
FROM(
SELECT p.id, p.name,
SUM(oi.quantity) as total_quantity
FROM Product p
JOIN OrderItems oi ON p.id = oi.product_id
GROUP BY p.id, p.name) as qt
JOIN Product p ON p.id = qt.id)
WHERE q_rank <= 3
-- 6. How many unique customers per month are there for the year 2016.
SELECT yt.month, COUNT(DISTINCT yt.id)
FROM (
(SELECT c.id, EXTRACT(YEAR FROM o.order_date) as year, EXTRACT(MONTH FROM o.order_date) as month
FROM Customer c
JOIN Orders o ON c.id = o.customer_id)) yt
GROUP BY yt.month, yt.year
HAVING yt.year = 2016
|
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript" src="node_modules/axios/dist/axios.js"></script>
</head>
<body>
<div id="vm">
<h1>{{msg}}</h1>
<a v-for="i in arr" :href="i.Url">{{i.Name}}</a>
</div>
<script type="text/javascript">
function getTxt(){
return axios.get("source/1.txt");
}
function getJson(){
return axios.get("source/test.json");
}
var vm=new Vue({
el:"#vm",
data:{
msg:"",
arr:[]
},
mounted:function(){
var that=this;
axios.all([getTxt(),getJson()])
.then(axios.spread(function(res1,res2){
console.log(res1.data)
that.msg=res1.data;
console.log(res2.data)
that.arr=res2.data.sites;
}))
}
})
</script>
</body>
</html>
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shopping List Check Off</title>
<link rel="stylesheet" href="styles/bootstrap.min.css">
<style>
.emptyMessage {
font-weight: bold;
color: red;
font-size: 1.2em;
}
li {
margin-bottom: 7px;
font-size: 1.2em;
}
li > button {
margin-left: 6px;
}
button > span {
color: green;
}
</style>
</head>
<body ng-app="ShoppingListCheckOff">
<div class="container">
<h1>Shopping List Check Off</h1>
<div class="row">
<!-- To Buy List -->
<div class="col-md-6" ng-controller="ToBuyShoppingController as toBuy">
<h2>To Buy:</h2>
<ul>
<li ng-repeat="item in toBuy.items">
Buy {{ item.quantity }} {{ item.name }}
<button ng-click="toBuy.buy($index)" class="btn btn-default">
<span class="glyphicon glyphicon-ok"></span>Bought
</button>
</li>
</ul>
<div class="emptyMessage" ng-if="toBuy.items.length == 0">Everything is bought!</div>
</div>
<!-- Already Bought List -->
<div class="col-md-6" ng-controller="AlreadyBoughtShoppingController as bought">
<h2>Already Bought:</h2>
<ul>
<li ng-repeat="item in bought.items">
Bought {{ item.quantity }} {{ item.name }}
</li>
</ul>
<div class="emptyMessage" ng-if="bought.items.length == 0">
Nothing bought yet.
</div>
</div>
</div> <!-- row -->
</div> <!-- container -->
<script src="angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
|
<!-- Hereda de una plantilla base llamada "base.html" -->
{% extends "base.html" %}
<!-- Herramientas para gestionar recursos estáticos y ajustes en los widgets -->
{% load static %}
{% load widget_tweaks %}
<!-- Inicio del bloque de contenido -->
{% block content %}
<!-- Estilos específicos para la página de registro -->
<style>
/* Color de fondo de la página completa */
body {
background-color: #e6f7ff;
}
/* Estilo del contenedor del formulario de registro */
.register-container {
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 30px;
}
/* Estilo del botón principal para enviar el formulario */
.btn-primary {
background-color: #007BFF;
border: none;
margin-top: 20px;
}
.btn-primary:hover {
background-color: #0056b3;
}
/* Estilo de los enlaces */
a {
color: #007BFF;
}
a:hover {
color: #0056b3;
text-decoration: underline;
}
/* Estilos adicionales para mejorar la presentación del formulario */
form p {
margin-bottom: 20px;
}
.form-control {
border-radius: 5px;
box-shadow: none;
}
.form-control:focus {
border-color: #007BFF;
box-shadow: 0 0 5px rgba(0, 128, 255, 0.5);
}
</style>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6 register-container">
<!-- Título del formulario de registro -->
<h2 class="mb-4 text-center">Registro</h2>
<!-- Formulario de registro -->
<form method="post">
{% csrf_token %} <!-- Token de seguridad para prevenir ataques CSRF -->
<!-- Campo de correo electrónico con su etiqueta, widget y mensaje de error si lo hay -->
<label for="{{ form.email.id_for_label }}">Correo electrónico:</label>
{{ form.email|add_class:"form-control mb-3" }}
{% if form.email.errors %}
<div class="text-danger">{{ form.email.errors.0 }}</div>
{% endif %}
<small class="text-muted">Debes usar un correo con dominio outlook.com, gmail.com o hotmail.com.</small>
<!-- Campo de nombre de usuario con su etiqueta, widget y mensaje de error si lo hay -->
<label for="{{ form.username.id_for_label }}">Nombre de usuario:</label>
{{ form.username|add_class:"form-control mb-3" }}
{% if form.username.errors %}
<div class="text-danger">{{ form.username.errors.0 }}</div>
{% endif %}
<!-- Campo de contraseña con su etiqueta, widget y mensaje de error si lo hay -->
<label for="{{ form.password1.id_for_label }}">Contraseña:</label>
{{ form.password1|add_class:"form-control mb-3" }}
{% if form.password1.errors %}
<div class="text-danger">{{ form.password1.errors.0 }}</div>
{% endif %}
<small class="text-muted">Mínimo 6 caracteres, al menos 1 mayúscula, 2 números y 1 caracter especial.</small>
<!-- Campo de confirmación de contraseña con su etiqueta, widget y mensaje de error si lo hay -->
<label for="{{ form.password2.id_for_label }}">Confirmar contraseña:</label>
{{ form.password2|add_class:"form-control mb-3" }}
{% if form.password2.errors %}
<div class="text-danger">{{ form.password2.errors.0 }}</div>
{% endif %}
<!-- Botón de envío del formulario -->
<button type="submit" class="btn btn-primary w-100">Registrar</button>
</form>
<!-- Enlace a la página de inicio de sesión si el usuario ya tiene una cuenta -->
<div class="mt-3 text-center">
¿Ya tienes una cuenta? <a href="{% url 'login' %}">Inicia sesión aquí</a>
</div>
</div>
</div>
</div>
{% endblock %}
|
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Permission;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::user()->hasPermissionTo('access admin cp', 'web')) {
return redirect('/admin-cp');
}
return redirect('/');
}
return $next($request);
}
}
|
<?php
namespace Patterns\Chapter3\StarbuzzCoffeFirst;
class Soy extends CondimentDecorator
{
private Beverage $beverage;
public function __construct(Beverage $beverage)
{
$this->beverage = $beverage;
$this->description = "Soy";
}
public function getDescription()
{
return $this->beverage->getDescription() . ", Soy";
}
public function cost()
{
return 0.5 + $this->beverage->cost();
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\UserType;
use Illuminate\Http\Request;
class ClerkController extends Controller
{
public function __construct()
{
$this->middleware(['role:admin']);
}
/**
* Display a listing of the resource.
*/
public function index()
{
$clerks = User::whereIn('user_type_id', UserType::select('id')->where('description','Clerk'))->get();
return view('clerks.index',compact('clerks'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('clerks.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$request->validate([
'email' => 'email|required|unique:users',
'firstname' => 'required',
'lastname' => 'required',
'password' => 'required|min:8',
]);
$clerkType = UserType::where('description','Clerk')->first();
$clerkType->users()->create($request->all());
return redirect(route('clerks.index'))->with('success','Successfully added a clerk!');
}
/**
* Display the specified resource.
*/
public function show(User $clerk)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(User $clerk)
{
return view('clerks.edit',['clerk' => $clerk]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, User $clerk)
{
$request->validate([
'email' => 'email|required|unique:users,email,' . $clerk->id,
'firstname' => 'required',
'lastname' => 'required',
]);
$clerk->email = $request->input('email');
$clerk->firstname = $request->input('firstname');
$clerk->lastname = $request->input('lastname');
if($request->has('password') && !empty($request->input('password'))){
$clerk->password = $request->input('password');
}
$clerk->save();
return redirect(route('clerks.index'))->with('success','Successfully updated clerk!');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(User $clerk)
{
$clerk->delete();
return redirect(route('clerks.index'))->with('success','Successfully deleted clerk!');
}
public function confirmDelete(User $clerk)
{
return view('clerks.confirm', ['clerk' => $clerk]);
}
}
|
'use client';
import Image from 'next/image';
import styles from './styles.module.css';
import logo from '../../../public/logo-rs.png';
import { NavMenu } from './navMenu';
import { useState } from 'react';
import { NavMenuMobile } from './navMenuMobile';
import { useScrollBlock } from '@/hooks';
export const Header = () => {
const [isNavMenuMobileOpen, setIsNavMenuMobileOpen] = useState(false);
const [blockScroll, allowScroll] = useScrollBlock();
const borderTop = (color: string) => (
<div style={{ backgroundColor: color }} className={styles['border-top']} />
);
const handleOpen = () => {
setIsNavMenuMobileOpen(true);
blockScroll();
};
const handleClose = () => {
setIsNavMenuMobileOpen(false);
allowScroll();
};
return (
<header className={styles['wrapper-header']}>
<div className={styles['group-border-top']}>
{borderTop('#52611A')} {borderTop('#850F23')} {borderTop('#D9A14A')}
</div>
{isNavMenuMobileOpen ? (
<NavMenuMobile handleClose={handleClose} />
) : (
<>
<Image src={logo} alt="Rio grande do sul logo" />
<NavMenu handleOpen={handleOpen} />
</>
)}
</header>
);
};
|
import React, { Component } from "react";
import { reduxForm, Field } from "redux-form";
import { connect } from "react-redux";
import { FormGroup, Col, Label, Input, Row, Button } from "reactstrap";
import DestinationValidation from "../validations/DestinationValidation";
const renderField = ({
input,
type,
placeholder,
label,
disabled,
readOnly,
meta: { touched, error, warning },
}) => (
<Row>
<Col md="12">
<Label htmlFor="{input}" className="col-form-label">
{label}
</Label>
</Col>
<Col md="12">
<Input
{...input}
type={type}
placeholder={placeholder}
disabled={disabled}
readOnly={readOnly}
></Input>
{touched &&
((error && <p style={{ color: "red" }}>{error}</p>) ||
(warning && <p style={{ color: "brown" }}>{warning}</p>))}
</Col>
</Row>
);
const mapStateToProps = (state) => {
return {
initialValues : {
city_id : state.destination.getDestinationDetail.city_id,
nama_destinasi : state.destination.getDestinationDetail.nama_destinasi,
tipe_destinasi : state.destination.getDestinationDetail.tipe_destinasi,
deskripsi_destinasi : state.destination.getDestinationDetail.deskripsi_destinasi,
koordinat_destinasi : state.destination.getDestinationDetail.koordinat_destinasi,
}
};
};
class DestinationFormComponent extends Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<FormGroup row>
<Col md={6}>
<FormGroup>
<Field
type="text"
name="city_id"
component={renderField}
label="ID Kota :"
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Field
type="text"
name="nama_destinasi"
component={renderField}
label="Nama Destinasi :"
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Field
type="text"
name="tipe_destinasi"
component={renderField}
label="Tipe Destinasi :"
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Field
type="text"
name="deskripsi_destinasi"
component={renderField}
label="Deskripsi :"
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Field
type="text"
name="koordinat_destinasi"
component={renderField}
label="Koordinat :"
/>
</FormGroup>
</Col>
</FormGroup>
<FormGroup row>
<Col md="12">
<FormGroup>
<Button
color="dark"
type="submit"
disabled={this.props.submitting}
>
Submit
</Button>
</FormGroup>
</Col>
</FormGroup>
</form>
);
}
}
DestinationFormComponent = reduxForm({
form: "formCreateDestination",
validate: DestinationValidation,
enableReinitialize: true,
})(DestinationFormComponent);
export default connect(mapStateToProps, null)(DestinationFormComponent);
|
/**
* Copyright 2009-2020 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.type;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
/**
* @author Clinton Begin
*/
public enum JdbcType {
/*
* This is added to enable basic support for the
* ARRAY data type - but a custom type handler is still required
*/
ARRAY(Types.ARRAY),
BIT(Types.BIT),
TINYINT(Types.TINYINT),
SMALLINT(Types.SMALLINT),
INTEGER(Types.INTEGER),
BIGINT(Types.BIGINT),
FLOAT(Types.FLOAT),
REAL(Types.REAL),
DOUBLE(Types.DOUBLE),
NUMERIC(Types.NUMERIC),
DECIMAL(Types.DECIMAL),
CHAR(Types.CHAR),
VARCHAR(Types.VARCHAR),
LONGVARCHAR(Types.LONGVARCHAR),
DATE(Types.DATE),
TIME(Types.TIME),
TIMESTAMP(Types.TIMESTAMP),
BINARY(Types.BINARY),
VARBINARY(Types.VARBINARY),
LONGVARBINARY(Types.LONGVARBINARY),
NULL(Types.NULL),
OTHER(Types.OTHER),
BLOB(Types.BLOB),
CLOB(Types.CLOB),
BOOLEAN(Types.BOOLEAN),
CURSOR(-10), // Oracle
UNDEFINED(Integer.MIN_VALUE + 1000),
NVARCHAR(Types.NVARCHAR), // JDK6
NCHAR(Types.NCHAR), // JDK6
NCLOB(Types.NCLOB), // JDK6
STRUCT(Types.STRUCT),
JAVA_OBJECT(Types.JAVA_OBJECT),
DISTINCT(Types.DISTINCT),
REF(Types.REF),
DATALINK(Types.DATALINK),
ROWID(Types.ROWID), // JDK6
LONGNVARCHAR(Types.LONGNVARCHAR), // JDK6
SQLXML(Types.SQLXML), // JDK6
DATETIMEOFFSET(-155), // SQL Server 2008
TIME_WITH_TIMEZONE(Types.TIME_WITH_TIMEZONE), // JDBC 4.2 JDK8
TIMESTAMP_WITH_TIMEZONE(Types.TIMESTAMP_WITH_TIMEZONE); // JDBC 4.2 JDK8
public final int TYPE_CODE;
private static Map<Integer,JdbcType> codeLookup = new HashMap<>();
static {
for (JdbcType type : JdbcType.values()) {
codeLookup.put(type.TYPE_CODE, type);
}
}
JdbcType(int code) {
this.TYPE_CODE = code;
}
public static JdbcType forCode(int code) {
return codeLookup.get(code);
}
}
|
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class VideoPlayerWidget extends StatefulWidget {
final String url;
const VideoPlayerWidget({super.key, required this.url});
@override
State<VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}
class _VideoPlayerWidgetState extends State<VideoPlayerWidget> {
late VideoPlayerController _videoPlayerController;
late ChewieController _chewieController;
@override
void initState() {
super.initState();
_videoPlayerController =
VideoPlayerController.networkUrl(Uri.parse(widget.url));
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController,
autoPlay: false,
looping: false,
);
_videoPlayerController.initialize().then((_) {
setState(() {}); // Refresh to reflect the new video
});
}
@override
void dispose() {
_videoPlayerController.dispose();
_chewieController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return _videoPlayerController.value.isInitialized
? AspectRatio(
aspectRatio: _videoPlayerController.value.aspectRatio,
child: Chewie(
controller: _chewieController,
),
)
: const Center(child: CircularProgressIndicator());
}
}
|
*
* This file is a part of digiKam project
* http://www.digikam.org
*
* Date : 2004-06-04
* Description : image plugins loader for image editor.
*
* Copyright (C) 2004-2005 by Renchi Raju <[email protected]>
* Copyright (C) 2004-2007 by Gilles Caulier <caulier dot gilles at gmail dot com>
*
* 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, 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.
*
#ifndef IMAGEPLUGINLOADER_H
#define IMAGEPLUGINLOADER_H
// Qt includes.
#include <qobject.h>
#include <qptrlist.h>
#include <qstring.h>
#include <qvaluelist.h>
#include <qpair.h>
// Local includes.
#include "digikam_export.h"
#include "imageplugin.h"
namespace Digikam
{
class SplashScreen;
class ImagePluginLoaderPrivate;
class DIGIKAM_EXPORT ImagePluginLoader : public QObject
{
public:
ImagePluginLoader(QObject *parent, SplashScreen *splash=0);
~ImagePluginLoader();
static ImagePluginLoader* instance();
QPtrList<ImagePlugin> pluginList();
void loadPluginsFromList(const QStringList& list);
// Return true if plugin library is loaded in memory.
// 'libraryName' is internal plugin library name not i18n.
bool pluginLibraryIsLoaded(const QString& libraryName);
ImagePlugin* pluginInstance(const QString& libraryName);
private:
ImagePlugin* pluginIsLoaded(const QString& name);
private:
static ImagePluginLoader *m_instance;
ImagePluginLoaderPrivate *d;
};
} // namespace Digikam
#endif /* IMAGEPLUGINLOADER_H */
|
import { useState, useEffect, useRef } from "react";
import axios from "axios";
import { NavLink } from "react-router-dom";
import { HiOutlineMagnifyingGlass } from "react-icons/hi2";
const SearchBar = () => {
const searchRef = useRef(null); // Referencia al input de búsqueda
const [searchName, setSearchName] = useState({
name: "",
});
const [game, setGame] = useState([]);
useEffect(() => {
const handleOutsideClick = (event) => {
// Comprobar si se hizo clic fuera del input de búsqueda
if (searchRef.current && !searchRef.current.contains(event.target)) {
setSearchName({ name: "" });
setGame([]);
}
};
window.addEventListener("click", handleOutsideClick);
return () => {
window.removeEventListener("click", handleOutsideClick);
};
}, []);
const handleChange = async (event) => {
const inputValue = event.target.value;
setSearchName({ name: inputValue });
if (inputValue.length === 0) {
setGame([]);
return;
}
const response = await axios.get(
`https://bckndll.onrender.com/games/page?name=${inputValue}`
);
const matches = response.data.games.filter((match) =>
match.name.toLowerCase().includes(inputValue.toLowerCase())
);
const matchesWithFirstLetter = matches.filter((match) =>
match.name.toLowerCase().startsWith(inputValue.toLowerCase())
);
const finalMatches = [...matchesWithFirstLetter, ...matches];
const uniqueMatches = Array.from(new Set(finalMatches.map((match) => match.id))).map((id) =>
finalMatches.find((match) => match.id === id)
);
setGame(uniqueMatches.slice(0, 5));
};
return (
<div className="sticky">
<div className="flex gap-2">
<input
ref={searchRef}
placeholder="Search game..."
type="search"
value={searchName.name}
onChange={handleChange}
className="rounded text-center h-[30px] placeholder-center font-semibold text-black focus:outline-none"
/>
<button className="text-white text-lg font-semibold no-underline hover:text-gray-500">
<HiOutlineMagnifyingGlass size={30} />
</button>
</div>
{searchName.name.length !== 0 && (
<div className="origin-top-left absolute left-0 mt-2 w-full">
<div className="rounded-md shadow-lg bg-gray-200 bg-opacity-6 ring-1 ring-black ring-opacity-5 divide-y divide-gray-300">
{game.length !== 0 ? (
<div className="flex flex-col">
{game.map((match) => (
<NavLink
key={match.id}
to={`/games/${match.id}`}
className="border-b border-gray-300 bg-gray-200 text-black italic font-bold text-sm p-3 hover:bg-gray-300 hover:text-black text-center w-auto"
>
{match.name}
</NavLink>
))}
</div>
) : (
<button
className="border-b border-gray-300 bg-gray-200 text-black italic font-bold text-sm p-3 cursor-default"
>
No results
</button>
)}
</div>
</div>
)}
</div>
);
};
export default SearchBar;
|
---
lang: en-us
title: SMADirectory
viewport: width=device-width, initial-scale=1.0
---
# SMADirectory
SMADirectory utility (SMADirectory.exe) is used to manage OpCon
directories. The utility is specifically useful for keeping log and
report directories from using too much disk space.
Based upon user criteria and filters, the utility can be used to:
- Delete files
- Zip (compress) files
- Move files (for full recursive directories)
- Recover files (for full recursive directories)
## Backwards Compatibility
This directory cleanup utility is compatible with SMADeleteOldFiles and
ClearDir. Customers who wish to convert should contact [SMA Technologies]{.GeneralCompanyName}.
## Requirements
The SMADirectory utility requires the following:
- Microsoft LSAM
- Microsoft .NET Framework 4.5
## Syntax
This utility supports the following types of arguments: dash, forward
slash, and comma delimited.
-------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------
.png "Note icon") **NOTE:** [SMADirectory is standardized to use (US) English localization, exclusively. The utility only accepts US settings or command-line values.]
-------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------
### Dash Argument
The SMADirectory.exe program accepts arguments using dash.
The following is an example of the command-line syntax:
SMADirectory.exe -d "c:\\Test" -r -u -e \*.\*
-------------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------------------------------
.png "Note icon") **NOTE:** [To get the full capability of this utility, [SMA Technologies]{.GeneralCompanyName} recommends using the dash (-) argument.]
-------------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------------------------------
#### Parameters
The next table identifies all the acceptable parameters for this
argument.
+-----------+----------------+-----------------+-----------------+
| Parameter | Name | Default | Description |
| -b | Bin | By default, the | This parameter |
| | | program will | indicates to |
| | | recover the | recover the |
| | | files. | files in the |
| | | | default |
| | | | location: |
| | | | |
| | | | |
| | | | |
| | | | \<d |
| | | | riveTarget\>\\P |
| | | | rogramData\\OpC |
| | | | onxps\\MSLSAM\\ |
| | | | |
| | | | SMA |
| | | | Directory\\\<di |
| | | | rectoryTarget\> |
| | | | |
| | | | |
| | | | |
| | | | **Note:** If |
| | | | you wish to set |
| | | | a custom |
| | | | location, you |
| | | | may do so using |
| | | | the -o switch. |
+-----------+----------------+-----------------+-----------------+
| -B | No Bin | | This parameter |
| | | | indicates that |
| | | | no recovery |
| | | | will be |
| | | | performed. |
| | | | |
| | | | - If you |
| | | | enter -B |
| | | | (No |
| | | | recycle), |
| | | | then the |
| | | | program |
| | | | will not |
| | | | save a copy |
| | | | of the |
| | | | directory |
| | | | in the |
| | | | default |
| | | | location. |
| | | | You may be |
| | | | explicit |
| | | | about |
| | | | recovery |
| | | | using -b |
| | | | (recover). |
+-----------+----------------+-----------------+-----------------+
| -c | Time to Retain | 5D | This parameter |
| | | | specifies the |
| | | | length of time |
| | | | that files |
| | | | should be |
| | | | retained within |
| | | | the timespan. |
| | | | |
| | | | |
| | | | |
| | | | The value must |
| | | | be in the |
| | | | following form: |
| | | | |
| | | | \<Numbe |
| | | | r\>\<TimeSpan\> |
| | | | |
| | | | |
| | | | |
| | | | With TimeSpan |
| | | | represented as: |
| | | | |
| | | | D (day), H |
| | | | (hour), X |
| | | | (month), M |
| | | | (minute), S |
| | | | (second), or Y |
| | | | (year) |
| | | | |
| | | | |
| | | | |
| | | | For example: |
| | | | |
| | | | 5D (for 5 days) |
+-----------+----------------+-----------------+-----------------+
| -d | Directory Name | | This |
| | | | \[required\] | | | | | parameter |
| | | | specifies the |
| | | | folder to be |
| | | | cleaned up or |
| | | | moved. |
+-----------+----------------+-----------------+-----------------+
| -e | Extensions | | This |
| | | | \[required\] | | | | | parameter |
| | | | accepts "\|" to |
| | | | separate |
| | | | extensions and |
| | | | / or filters. |
| | | | |
| | | | |
| | | | |
| | | | For example: |
| | | | |
| | | | |
| | | | |
| | | | .txt\|.log |
| | | | |
| | | | **- or -** |
| | | | |
| | | | txt \| log |
| | | | |
| | | | |
| | | | |
| | | | The program |
| | | | also matches |
| | | | wildcard |
| | | | patterns as |
| | | | follows: |
| | | | |
| | | | |
| | | | |
| | | | \*File\*.\* |
| | | | |
| | | | **- or -** |
| | | | |
| | | | name\*.log |
| | | | |
| | | | **- or -** |
| | | | |
| | | | \".\" |
+-----------+----------------+-----------------+-----------------+
| -F | TimeType | FM | This parameter |
| | | | specifies the |
| | | | time type |
| | | | information on |
| | | | files for |
| | | | processing. |
| | | | |
| | | | |
| | | | |
| | | | The available |
| | | | values are: |
| | | | |
| | | | - FA (for |
| | | | last Access |
| | | | date) |
| | | | - FM (for |
| | | | last |
| | | | |
| | | | Modification |
| | | | date) |
| | | | - FC (for |
| | | | Creation |
| | | | date) |
+-----------+----------------+-----------------+-----------------+
| -h | No Hidden | By default, the | This parameter |
| | | program will | specifies not |
| | | process hidden | to process |
| | | and system | system and |
| | | files. | hidden files. |
+-----------+----------------+-----------------+-----------------+
| -m | Move | Null | This parameter |
| | | | specifies the |
| | | | path to which a |
| | | | folder will be |
| | | | moved. |
| | | | |
| | | | - If the -m |
| | | | and/or -z |
| | | | switches |
| | | | are |
| | | | entered, |
| | | | then the |
| | | | program |
| | | | will |
| | | | perform a |
| | | | move |
| | | | operation |
| | | | instead of |
| | | | a delete |
| | | | operation. |
| | | | - If the |
| | | | zip |
| | | | command |
| | | | was |
| | | | |
| | | | entered, |
| | | | the |
| | | | program |
| | | | will |
| | | | zip the |
| | | | folder. |
| | | | This |
| | | | case is |
| | | | the |
| | | | only |
| | | | |
| | | | scenario |
| | | | where |
| | | | the -x |
| | | | |
| | | | (delete) |
| | | | switch |
| | | | may be |
| | | | |
| | | | entered. |
+-----------+----------------+-----------------+-----------------+
| -o | RecoverPath | %Program | If recovery is |
| | | Data%/OpConxps/ | on, this |
| | | | parameter |
| | | SMADirectory | allows you to |
| | | | specify a |
| | | | location for a |
| | | | recovery copy |
| | | | of the |
| | | | Directory to |
| | | | process. This |
| | | | process will |
| | | | only recover |
| | | | qualifying |
| | | | files. |
+-----------+----------------+-----------------+-----------------+
| -r | Recursive | The process | This parameter |
| | | does not run | specifies to |
| | | recursively. | process |
| | | | subfolders and |
| | | | files under |
| | | | subfolders. |
+-----------+----------------+-----------------+-----------------+
| -u | Debug | | This parameter |
| | | | places the |
| | | | program in |
| | | | Debug mode. |
+-----------+----------------+-----------------+-----------------+
| -v | Verbose | No | This parameter |
| | | | to print |
| | | | non-deleted |
| | | | file names. |
+-----------+----------------+-----------------+-----------------+
| -x | Delete | By default, | When -m (move) |
| | | moved files are | or -z (zip) is |
| | | not deleted. | specified, the |
| | | | moved files can |
| | | | be also deleted |
| | | | by setting this |
| | | | switch. |
| | | | |
| | | | - The user |
| | | | can use the |
| | | | -x command |
| | | | to delete |
| | | | the files |
| | | | after the |
| | | | move path |
| | | | location if |
| | | | desired. |
| | | | |
| | | | - The -x |
| | | | command |
| | | | will delete |
| | | | the files |
| | | | under the |
| | | | MOVE path. |
| | | | The -x |
| | | | command is |
| | | | useful when |
| | | | the user |
| | | | only needs |
| | | | a zip file |
| | | | as the |
| | | | result. |
| | | | |
| | | | - Since |
| | | | we move |
| | | | the |
| | | | files |
| | | | to the |
| | | | MOVE |
| | | | PATH |
| | | | |
| | | | location, |
| | | | then we |
| | | | create |
| | | | the zip |
| | | | file |
| | | | the |
| | | | files |
| | | | under |
| | | | the |
| | | | MOVE |
| | | | PATH |
| | | | can be |
| | | | deleted |
| | | | using |
| | | | this |
| | | | option. |
+-----------+----------------+-----------------+-----------------+
| -z | Zip | By default, no | This parameter |
| | | file | compresses |
| | | compression | (zips) the |
| | | occurs. | files moved. |
| | | | Enter the name |
| | | | of the zip. |
| | | | |
| | | | - If the zip |
| | | | command was |
| | | | entered, |
| | | | the program |
| | | | will zip |
| | | | the folder. |
| | | | - This |
| | | | program is |
| | | | built with |
| | | | .Net 4.5 |
| | | | for |
| | | | windows; |
| | | | therefore, |
| | | | the |
| | | | compression |
| | | | process |
| | | | requires |
| | | | the |
| | | | compression |
| | | | utility |
| | | | that comes |
| | | | with any |
| | | | Windows |
| | | | operation |
| | | | system. |
| | | | - When the |
| | | | user enters |
| | | | the -z |
| | | | command, |
| | | | the user |
| | | | can also |
| | | | include the |
| | | | -m command. |
| | | | The user |
| | | | can only |
| | | | enter the |
| | | | -x command |
| | | | when both |
| | | | -m and -z |
| | | | are |
| | | | included. |
| | | | - The -z |
| | | | command |
| | | | requires |
| | | | the name of |
| | | | the file |
| | | | resulted on |
| | | | the |
| | | | compression |
| | | | when there |
| | | | is no -m |
| | | | |
| | | | (move) command |
| | | | entered. If |
| | | | there is no |
| | | | zip |
| | | | filename |
| | | | specified, |
| | | | then the |
| | | | program |
| | | | will use |
| | | | the |
| | | | following |
| | | | naming |
| | | | convention |
| | | | to set the |
| | | | filename: |
| | | | |
| | | | [zip.currentda | | | | | te.zip]{style=" |
| | | | font-family: 'C |
| | | | ourier New';"}. |
| | | | - The |
| | | | compression |
| | | | only occurs |
| | | | after the |
| | | | Move |
| | | | process is |
| | | | completed |
| | | | and the |
| | | | files are |
| | | | compressed |
| | | | in the -m |
| | | | path |
| | | | entered by |
| | | | the user. |
+-----------+----------------+-----------------+-----------------+
### Forward Slash Argument
The forward slash argument is supported for backwards compatibility with
cleardir.exe and can be used in the same way as the dash switches.
The following is an example of the command-line syntax:
SMADirectory.exe /d "c:\\Test" /r /u /e \*.\*
### Comma Delimited Argument
The comma delimited argument is supported for backwards compatibility
with the SMADeleteOldFiles and can only be used to delete files (not
move or compress them). This mode requires three (3) parameters to run
successfully.
The following command-line syntax can be used:
\<Target Directory\>\\OpConxps\\MSLSAM\\SMADirectory.exe
Directory,DaysToRetain,FileExtensions
#### Parameters
The following describes the command-line parameters:
- **\<Target Directory\>**: The path to the OpCon installation folder
(e.g., \"C:\\Program Files\\\").
- **Directory**: The path to the directory to examine.
- **DaysToRetain**: The number of days to keep in the directory.
- The counter must be entered in English. For example, 5d.
- The value must be greater than zero, but less than 32,757.
- **FileExtensions**: The file extensions to apply this retention
period to (e.g., \"log\" would look for files with the log
extension).
- One or more file extensions can be specified (separated by
commas).
- The wildcard (\*) character can be specified to apply this
retention period to all files in this directory.
#### Example
+----------------------------------+----------------------------------+
|  | older than 5 days: |
| .png "Example icon") | |
| | \"C:\\Program |
| | Files\\ |
| | OpConxps\\MSLSAM\\SMADirectory\" |
| | |
| | \"C:\\Program |
| | Data\\OpConxps\\SAM\\Log,5,log\" |
| | |
| | |
| | |
| | Notice that there is no period |
| | in front of log. |
+----------------------------------+----------------------------------+
## Exit Codes
The SMADirectory.exe program can exit with the following codes:
+-----------+-----------------+-----------------+-----------------+
| Exit Code | Sample Command | Message | Status |
| | | | Description |
| 202 | -e | | Less parameters |
+-----------+-----------------+-----------------+-----------------+
| 203 | -d C:\\Source | \[G | Wrong Counter | | | -c 20W | etTimeCounter\] | Letter |
| | | Invalid | |
| | | Counter. Cannot | |
| | | be equal or | |
| | | less than | |
| | | zero\... | |
| | | | |
| | | \[G | | | | | etTimeOptions\] | |
| | | Error while | |
| | | loading | |
| | | settings. | |
+-----------+-----------------+-----------------+-----------------+
| 203 | -d C:\\Source | \[G | Negative | | | -c -5D | etTimeCounter\] | Counter |
| | | Invalid | |
| | | Counter. Cannot | |
| | | be equal or | |
| | | less than | |
| | | zero\... | |
| | | | |
| | | \[G | | | | | etTimeOptions\] | |
| | | Error while | |
| | | loading | |
| | | settings. | |
+-----------+-----------------+-----------------+-----------------+
| 204 | -d C:\\Source | \[G | Zero Counter | | | -c 0D | etTimeCounter\] | |
| | | Invalid Counter | |
+-----------+-----------------+-----------------+-----------------+
| 205 | -d | The Directory | Directory |
| | C: | does not exits | specified is |
| | \\InvalidFolder | | invalid. |
| | -c 5d -e \*.\* | | |
+-----------+-----------------+-----------------+-----------------+
| 206 | -d C:\\Source | | Invalid Option. |
| | -c5D -e \*.log | | Zip File Name |
| | -2 | | is Required. |
+-----------+-----------------+-----------------+-----------------+
| 206 | -d C:\\Source | | Invalid |
| | -c5D | | Options. The -e |
| | | | is Required. |
+-----------+-----------------+-----------------+-----------------+
: Exit Codes when using Dash/Forward Slash Argument
Exit Code Sample Command Message Status Description
----------- ------------------------- ---------------------------------------------------------------------------------------------- ---------------------------------
202 C:\\Source \[Main\] Invalid number of arguments Less parameters 203 C:\\Source,5W,log \[ParseComaDelimited\]\[SetCounter\] Invalid Counter. Cannot be equal or less than zero\.... Invalid Counter Letter
203 C:\\Source,W,log \[ParseComaDelimited\]\[SetCounter\] Invalid Counter. Counter is not numeric Counter is a letter 204 C:\\Source,0,log \[ParseComaDelimited\]\[SetCounter\] Invalid Counter. Cannot be equal or less than zero\.... Zero Counter
204 C:\\Source,-5,log \[ParseComaDelimited\]\[SetCounter\] Invalid Counter. Cannot be equal or less than zero\.... Negative Counter 205 C:\\InvalidFolder,0,log The Directory does not exits Directory specified is invalid.
206 -d C:\\Source,5,log Exit Status 206 Invalid Options
: Exit Codes when using Comma Argument
:::
|
import { TextField as MuiTextField, TextFieldProps } from "@mui/material";
import { FieldInputProps, useField } from "formik";
type Props = { name: string } & TextFieldProps;
type TexFieldConfig = TextFieldProps & FieldInputProps<any>;
const FormikTextField = ({ name, ...props }: Props) => {
const [field, meta] = useField(name);
const configTextField: TexFieldConfig = {
...field,
...props,
};
if (meta.touched && meta.error) {
configTextField.error = true;
configTextField.helperText = meta.error;
}
return <MuiTextField {...configTextField} />;
};
export default FormikTextField;
|
use std::collections::{HashMap, HashSet, VecDeque};
use mortalsim_core::sim::component::SimComponent;
use mortalsim_core::sim::layer::circulation::{CirculationComponent, CirculationConnector};
use mortalsim_core::sim::organism::test::{TestBloodVessel, TestOrganism};
use mortalsim_core::substance::{Substance, SubstanceChange, SubstanceConcentration};
use mortalsim_core::SimTime;
use rand::distributions::{Alphanumeric, DistString};
pub struct SubstanceConcentrationRange {
min: SubstanceConcentration,
max: SubstanceConcentration,
}
impl SubstanceConcentrationRange {
#[allow(non_snake_case)]
pub fn new(min_uM: f64, max_uM: f64) -> Self {
Self {
min: SubstanceConcentration::from_uM(min_uM),
max: SubstanceConcentration::from_uM(max_uM),
}
}
pub fn check(&self, val: SubstanceConcentration) {
log::info!("Concentration {}. Expected range {} -> {}",
val,
self.min,
self.max
);
assert!(
val >= self.min && val <= self.max,
"Concentration {} is not within expected range {} -> {}",
val,
self.min,
self.max
);
}
}
pub struct TestBloodCheckerComponent {
/// Generated ID
id: &'static str,
/// Which vessel to associate with
vessel: TestBloodVessel,
/// List of time to execute, substance to change, how much
pending_writes: VecDeque<(SimTime, Substance, SubstanceChange)>,
/// List of time to read, substance to check, expected value
pending_reads: VecDeque<(SimTime, Substance, SubstanceConcentrationRange)>,
/// Circulation connector
circ_connector: CirculationConnector<TestOrganism>,
/// Prev
prev: HashMap<Substance, SubstanceConcentration>,
}
impl TestBloodCheckerComponent {
pub fn new(
vessel: TestBloodVessel,
mut writes: Vec<(SimTime, Substance, SubstanceChange)>,
mut reads: Vec<(SimTime, Substance, SubstanceConcentrationRange)>,
) -> Self {
writes.sort_by(|a, b| a.0.cmp(&b.0));
reads.sort_by(|a, b| a.0.cmp(&b.0));
Self {
id: Alphanumeric.sample_string(&mut rand::thread_rng(), 16).leak(),
vessel,
pending_writes: writes.into(),
pending_reads: reads.into(),
circ_connector: CirculationConnector::new(),
prev: HashMap::new(),
}
}
}
impl CirculationComponent<TestOrganism> for TestBloodCheckerComponent {
fn circulation_connector(&mut self) -> &mut CirculationConnector<TestOrganism> {
&mut self.circ_connector
}
fn circulation_init(&mut self, circulation_initializer: &mut mortalsim_core::sim::layer::circulation::CirculationInitializer<TestOrganism>) {
log::info!("Circ init {}", self.id);
circulation_initializer.attach_vessel(self.vessel);
for substance in self.pending_reads.iter().map(|(_, s, _e)| *s).collect::<HashSet<Substance>>() {
circulation_initializer.notify_composition_change(
self.vessel,
substance,
SubstanceConcentration::from_mM(0.0)
)
}
}
}
impl SimComponent<TestOrganism> for TestBloodCheckerComponent {
fn id(&self) -> &'static str {
self.id
}
fn attach(self, registry: &mut mortalsim_core::sim::component::ComponentRegistry<TestOrganism>) {
registry.add_circulation_component(self)
}
fn run(&mut self) {
let sim_time = self.circ_connector.sim_time();
// See if we need to write any substance changes
while self.pending_writes.len() > 0 && self.pending_writes.get(0).unwrap().0 <= sim_time {
let (_, substance, change) = self.pending_writes.pop_front().unwrap();
log::info!("Scheduling change on {:?}", self.vessel);
self.circ_connector
.blood_store(&self.vessel)
.unwrap()
.schedule_custom_change(substance, change);
}
if let Some((_, substance, _ex)) = self.pending_reads.get(0) {
let val = self.circ_connector
.blood_store(&self.vessel)
.unwrap()
.concentration_of(&substance);
if !self.prev.contains_key(substance) || (&val - self.prev.get(substance).unwrap()).molpm3 > 0.000001 {
log::info!("{}: {} {:?}: {}", self.circ_connector.sim_time(), self.id(), self.vessel, val);
}
self.prev.insert(*substance, val);
}
while self.pending_reads.len() > 0 && self.pending_reads.get(0).unwrap().0 <= sim_time {
let (_, substance, expected) = self.pending_reads.pop_front().unwrap();
log::info!("{}: Reading value on {:?}", sim_time, self.vessel);
let conc = self.circ_connector
.blood_store(&self.vessel)
.unwrap()
.concentration_of(&substance);
expected.check(conc);
}
}
}
|
import yaml
import jinja2
from django.db.models import Q
from lava_common.compat import yaml_safe_load
from lava_scheduler_app.models import (
Device,
DeviceType,
GroupDevicePermission,
GroupDeviceTypePermission,
)
from lava_scheduler_app.dbutils import (
load_devicetype_template,
invalid_template,
active_device_types,
)
from lava_server.files import File
from django.contrib.auth.models import User, Group, Permission
from django.test import TestCase
# python3 needs print to be a function, so disable pylint
class ModelFactory:
def __init__(self):
self._int = 0
def getUniqueInteger(self):
self._int += 1
return self._int
def getUniqueString(self, prefix="generic"):
return "%s-%d" % (prefix, self.getUniqueInteger())
def get_unique_user(self, prefix="generic"):
return "%s-%d" % (prefix, User.objects.count() + 1)
def get_unique_group(self, prefix="group"):
return "%s-%d" % (prefix, Group.objects.count() + 1)
def make_user(self):
return User.objects.create_user(
self.get_unique_user(),
"%[email protected]" % (self.getUniqueString(),),
self.getUniqueString(),
)
def make_group(self):
return Group.objects.create(name=self.get_unique_group())
class TestCaseWithFactory(TestCase):
def setUp(self):
TestCase.setUp(self)
self.factory = ModelFactory()
class DeviceTest(TestCaseWithFactory):
def test_device_permissions_test(self):
dt = DeviceType(name="type1")
dt.save()
device = Device(device_type=dt, hostname="device1")
device.save()
group = self.factory.make_group()
user1 = self.factory.make_user()
user1.groups.add(group)
group2 = self.factory.make_group()
user2 = self.factory.make_user()
user2.groups.add(group2)
GroupDevicePermission.objects.assign_perm("submit_to_device", group, device)
self.assertEqual(device.can_submit(user2), False)
self.assertEqual(device.can_submit(user1), True)
GroupDevicePermission.objects.remove_perm("submit_to_device", group, device)
self.assertEqual(device.can_view(user2), True)
self.assertEqual(device.can_view(user1), True)
GroupDeviceTypePermission.objects.assign_perm("view_devicetype", group, dt)
self.assertEqual(device.can_view(user2), False)
self.assertEqual(device.can_view(user1), True)
GroupDeviceTypePermission.objects.remove_perm("view_devicetype", group, dt)
GroupDevicePermission.objects.assign_perm("view_device", group, device)
self.assertEqual(device.can_view(user2), False)
self.assertEqual(device.can_view(user1), True)
GroupDevicePermission.objects.assign_perm("view_device", group2, device)
self.assertEqual(device.can_view(user2), True)
self.assertEqual(device.can_view(user1), True)
device.health = Device.HEALTH_RETIRED
device.save()
self.assertEqual(device.can_submit(user2), False)
self.assertEqual(device.can_submit(user1), False)
# Test that global permission works as intended.
user3 = self.factory.make_user()
user3.user_permissions.add(Permission.objects.get(codename="change_device"))
self.assertEqual(device.can_change(user3), True)
class DeviceTypeTest(TestCaseWithFactory):
def tearDown(self):
super().tearDown()
Device.objects.all().delete()
DeviceType.objects.all().delete()
"""
Test loading of device-type information
"""
def test_device_type_parser(self):
data = load_devicetype_template("beaglebone-black")
self.assertIsNotNone(data)
self.assertIn("actions", data)
self.assertIn("deploy", data["actions"])
self.assertIn("boot", data["actions"])
def test_device_type_templates(self):
"""
Ensure each template renders valid YAML
"""
env = jinja2.Environment( # nosec - YAML, not HTML, no XSS scope.
loader=File("device-type").loader(), trim_blocks=True, autoescape=False
)
for template_name in File("device-type").list("*.jinja2"):
try:
template = env.get_template(template_name)
except jinja2.TemplateNotFound as exc:
self.fail("%s: %s" % (template_name, exc))
data = None
try:
data = template.render()
yaml_data = yaml_safe_load(data)
except yaml.YAMLError as exc:
print(data) # for easier debugging - use the online yaml parser
self.fail("%s: %s" % (template_name, exc))
self.assertIsInstance(yaml_data, dict)
def test_retired_invalid_template(self):
name = "beaglebone-black"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(device_type=dt, hostname="bbb-01", health=Device.HEALTH_RETIRED)
device.save()
device.refresh_from_db()
self.assertEqual(
[],
list(
Device.objects.filter(
Q(device_type=dt), ~Q(health=Device.HEALTH_RETIRED)
)
),
)
self.assertIsNotNone([d for d in Device.objects.filter(device_type=dt)])
self.assertFalse(invalid_template(device.device_type))
def test_bbb_valid_template(self):
name = "beaglebone-black"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(device_type=dt, hostname="bbb-01", health=Device.HEALTH_GOOD)
device.save()
device.refresh_from_db()
self.assertIsNotNone([d for d in Device.objects.filter(device_type=dt)])
self.assertTrue(File("device-type", name).exists())
self.assertIsNotNone([device in Device.objects.filter(device_type=dt)])
self.assertIsNotNone(device.load_configuration())
self.assertTrue(bool(load_devicetype_template(device.device_type.name)))
self.assertFalse(invalid_template(device.device_type))
def test_unknown_invalid_template(self):
name = "nowhere-never-skip"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(device_type=dt, hostname="test-01", health=Device.HEALTH_GOOD)
device.save()
device.refresh_from_db()
self.assertIsNotNone([d for d in Device.objects.filter(device_type=dt)])
self.assertIsNone(device.load_configuration())
self.assertIsNotNone([device in Device.objects.filter(device_type=dt)])
self.assertFalse(bool(load_devicetype_template(device.device_type.name)))
self.assertTrue(invalid_template(device.device_type))
def test_juno_vexpress_valid_template(self):
name = "juno-r2"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(
device_type=dt, hostname="juno-r2-01", health=Device.HEALTH_GOOD
)
device.save()
device.refresh_from_db()
self.assertIsNotNone([d for d in Device.objects.filter(device_type=dt)])
self.assertFalse(File("device-type", "juno-r2").exists())
self.assertEqual("juno-r2-01", device.hostname)
self.assertIsNotNone(device.load_configuration())
self.assertEqual(
[device], [device for device in Device.objects.filter(device_type=dt)]
)
self.assertEqual("juno", device.get_extends())
self.assertFalse(bool(load_devicetype_template(device.device_type.name)))
self.assertFalse(invalid_template(device.device_type))
def test_active_device_types(self):
name = "beaglebone-black"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(device_type=dt, hostname="bbb-01", health=Device.HEALTH_GOOD)
device.save()
device = Device(device_type=dt, hostname="bbb-02", health=Device.HEALTH_RETIRED)
device.save()
name = "juno-r2"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(
device_type=dt, hostname="juno-r2-01", health=Device.HEALTH_RETIRED
)
device.save()
name = "juno"
dt = DeviceType(name=name)
dt.display = False
dt.save()
dt.refresh_from_db()
dt.refresh_from_db()
device = Device(
device_type=dt, hostname="juno-01", health=Device.HEALTH_UNKNOWN
)
device.save()
name = "qemu"
dt = DeviceType(name=name)
dt.save()
dt.refresh_from_db()
device = Device(device_type=dt, hostname="qemu-01", health=Device.HEALTH_GOOD)
device.save()
self.assertEqual(
{"bbb-01", "bbb-02", "juno-r2-01", "qemu-01", "juno-01"},
set(Device.objects.all().values_list("hostname", flat=True)),
)
self.assertEqual(
{"beaglebone-black", "juno", "juno-r2", "qemu"},
set(DeviceType.objects.values_list("name", flat=True)),
)
# exclude juno-r2 because all devices of that device-type are retired.
# exclude juno because the device_type is set to not be displayed.
# include beaglebone-black because not all devices of that type are retired.
# include qemu because none of the devices of that type are retired.
self.assertEqual(
{"beaglebone-black", "qemu"},
set(active_device_types().values_list("name", flat=True)),
)
|
//
// FavoritesViewModelTests.swift
// VideoGamesAppTests
//
// Created by Metin Tarık Kiki on 28.07.2023.
//
import Foundation
import XCTest
@testable import VideoGamesApp
import RAWG_API
final class FavoritesViewModelTests: XCTestCase {
var viewModel: FavoritesViewModelProtocol!
var coordinator = MockMainCoordinator()
var coreDataService = MockCoreDataManager()
static let mockDataFilterName = "testName"
var testFilterName: String?
var mockData: RAWG_GameDetails = .init(
id: 1,
name: mockDataFilterName,
metacritic: 90,
released: "2023-07-03",
rating: 3.5
)
var didNavigate: Bool {
return coordinator.invokeCountNavigate > 0
}
override func setUpWithError() throws {
viewModel = FavoritesViewModel(
coordinator: coordinator,
coreDataService: coreDataService
)
coreDataService.addGameToFavorites(mockData)
testFilterName = FavoritesViewModelTests.mockDataFilterName
}
override func tearDownWithError() throws {
viewModel = nil
coreDataService.removeGameFromFavorites(Int32(mockData.id!))
}
func testFetchFavorites() {
XCTAssertTrue(viewModel.itemCount == 0)
viewModel.updateFavoriteGames(for: nil)
XCTAssertTrue(viewModel.itemCount > 0)
}
func testFilter() {
viewModel.updateFavoriteGames(for: nil)
XCTAssertTrue(viewModel.itemCount > 0)
viewModel.filter(for: "123")
XCTAssertTrue(viewModel.itemCount == 0)
viewModel.filter(for: testFilterName)
XCTAssertTrue(viewModel.itemCount == 1)
}
func testFavoriteCell() {
viewModel.updateFavoriteGames(for: nil)
XCTAssertNil(viewModel.getGame(at: 999))
XCTAssertNotNil(viewModel.getGame(at: 0))
viewModel.didSelectGame(at: 999)
XCTAssertFalse(didNavigate)
viewModel.didSelectGame(at: 0)
XCTAssertTrue(didNavigate)
}
}
|
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css">
<script src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Patients </a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" th:href="@{/}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Informations </a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-bs-toggle="dropdown" aria-expanded="false">
Patients
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li sec:authorize="hasRole('ADMIN')"><a class="dropdown-item" th:href="@{/admin/formPatients}">Nouveau
Patients </a></li>
<li><a class="dropdown-item" th:href="@{/user/index}">Chercher </a></li>
<li>
<hr class="dropdown-divider">
</li>
</ul>
</li>
</ul>
<ul class="navbar-nav" sec:authorize="!isAuthenticated()">
<li class="nav-item dropdown">
<a class="dropdown-item" th:href="@{/login}">[Login]</a>
</li>
</ul>
<ul class="navbar-nav" sec:authorize="isAuthenticated()">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-bs-toggle="dropdown" aria-expanded="false">
<span sec:authentication="name"></span>
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" th:href="@{/logout}">[Logout]</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<section layout:fragment="content"></section>
</body>
</html>
|
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from 'src/app/models/user';
import { CognitoService } from 'src/app/services/cognito.service';
@Component({
selector: 'app-iniciar-sesion',
templateUrl: './iniciar-sesion.component.html',
styleUrls: ['./iniciar-sesion.component.css']
})
export class IniciarSesionComponent implements OnInit {
user: User | undefined;
alertMessage: string = '';
showAlert: boolean = false;
olvidoPassword: boolean = false;
isForgotPassword: boolean = false;
newPassword: string = '';
constructor(private router: Router, private cognitoService: CognitoService) { }
ngOnInit(): void {
this.user = {} as User;
}
signInWithCognito() {
if (this.user && this.user.email && this.user.password) {
this.cognitoService.signIn(this.user).then(() => {
this.router.navigate(['/'])
}).catch((error: any) => {
this.displayAlert(error.message);
})
} else {
this.displayAlert('Ingrese un email y/o una contraseña valida')
}
}
forgotPassWordClicked() {
if (this.user && this.user.email) {
this.cognitoService.forgotPassword(this.user).then(() => {
this.isForgotPassword = true;
}).catch((error: any) => {
this.displayAlert(error.message);
})
} else {
this.displayAlert('Para recuperar su contraseña ingrese en el campo Email un mail valido y vuelva a tocar olvido su contraseña')
}
}
newPasswordSubmit() {
if (this.user && this.user.code && this.newPassword) {
this.cognitoService.forgotPasswordSubmit(this.user, this.newPassword.trim()).then(() => {
this.displayAlert("Contraseña actualizada");
this.isForgotPassword = false;
}).catch((error: any) => {
this.displayAlert(error.message);
})
} else {
this.displayAlert("Por favor ingrese bien los datos");
}
}
private displayAlert(message: string) {
this.alertMessage = message;
this.showAlert = true;
}
}
|
function seek(entity, target) {
// Calculate the desired velocity as a vector pointing from the entity to the target.
let desiredVelocity = subtractVectors(target.position, entity.position);
// Normalize the desired velocity to get it in the direction of the target only.
desiredVelocity = normalize(desiredVelocity);
// Multiply the normalized vector by the entity's maximum speed to get the maximum desired velocity.
desiredVelocity = multiplyVector(desiredVelocity, entity.maxSpeed);
// Calculate the steering force as the difference between the desired velocity and the entity's current velocity.
let steeringForce = subtractVectors(desiredVelocity, entity.velocity);
// Return the steering force which will adjust the entity's velocity in the next update.
return steeringForce;
}
function flee(entity, target) {
// Calculate the vector from the entity to the target
let desiredVelocity = subtractVectors(entity.position, target.position);
desiredVelocity = normalize(desiredVelocity); // Normalize to get the direction
desiredVelocity = multiplyVector(desiredVelocity, entity.maxSpeed); // Scale to maximum speed
// The steering force is the difference between desired velocity and current velocity
let steeringForce = subtractVectors(desiredVelocity, entity.velocity);
// Return the computed steering force to adjust the entity's velocity away from the target
return steeringForce;
}
function wander(entity) {
// Parameters for wander behavior
let wanderRadius = 10; // Radius of the wander circle
let wanderDistance = 15; // Distance the wander circle is in front of the entity
let wanderJitter = 1; // How much the target point can change each tick
// Initialize entity.target to the entity's current position if it doesn't exist
// Creates a shallow copy of entity.position & assigns to entity.target so target won't affect position
entity.target = entity.target || [...entity.position];
// Add a small random vector to the target's position
let randomDisplcement = [
entity.wanderTarget[0] += Math.random() * wanderJitter - wanderJitter * 0.5;
entity.wanderTarget[1] += Math.random() * wanderJitter - wanderJitter * 0.5;
];
randomDisplacement = normalize(randomDisplacement);
randomDisplacement = multiplyVector(randomDisplacement, wanderRadius);
// Calculate the forward vector based on the entity's orientation
let forwardVector = multiplyVector(orientationToVector(entity.orientation), wanderDistance);
// Combine the forward vector and random displacement to get the target in local space
let targetLocal = addVectors(forwardVector, randomDisplacement);
// Convert the local target to world space using the entity's current position
entity.target = addVectors(entity.position, targetLocal);
// Seek towards the target
return seek(entity, {position: targetWorld});
}
function directMovement(entity, direction) {
// Assuming 'direction' is a normalized vector representing the desired direction of movement
let desiredVelocity = multiplyVector(direction, entity.maxSpeed);
// Update entity's velocity directly towards the desired direction
entity.velocity = desiredVelocity;
// Calculate the steering force required to align the entity's current velocity with the desired velocity
let steeringForce = subtractVectors(desiredVelocity, entity.velocity);
return steeringForce;
}
// Subtracts one vector from another and returns the resulting vector.
function subtractVectors(vector1, vector2) {
return [vector1[0] - vector2[0], vector1[1] - vector2[1]];
}
// Normalizes a vector to a unit vector (length of 1), maintaining its direction.
function normalize(vector) {
const length = Math.sqrt(vector[0] ** 2 + vector[1] ** 2); // Calculate the vector's length.
if (length === 0) return [0, 0]; // Handle the zero-length case to avoid division by zero.
return [vector[0] / length, vector[1] / length]; // Scale the vector components to normalize it.
}
// Multiplies a vector by a scalar and returns the resulting scaled vector.
function multiplyVector(vector, scalar) {
return [vector[0] * scalar, vector[1] * scalar]; // Scale both components of the vector.
}
// Adds two vectors together and returns the resulting vector.
function addVectors(vector1, vector2) {
return [vector1[0] + vector2[0], vector1[1] + vector2[1]]; // Add corresponding components.
}
// Converts local space coordinates to world space based on position and orientation.
function localToWorld(position, orientation, localPoint) {
// Assuming orientation is in radians and points are [x, y]
let cosTheta = Math.cos(orientation); // Cosine of the orientation angle.
let sinTheta = Math.sin(orientation); // Sine of the orientation angle.
// Calculate the world coordinates by rotating and then translating the local point.
let worldX = cosTheta * localPoint[0] - sinTheta * localPoint[1] + position[0];
let worldY = sinTheta * localPoint[0] + cosTheta * localPoint[1] + position[1];
return [worldX, worldY]; // Return the transformed coordinates.
}
|
import 'package:flutter/material.dart';
class CustomForm extends StatelessWidget {
final String? hintText;
final Color? containerColor;
final TextInputType? keyboardType;
final String? initialValue;
final bool? obscureText;
final Function(String)? onChanged;
final String? Function(String?)? validator;
final Color? iconColor;
final Color? borderColor;
final IconData? iconData;
final VoidCallback? suffixIconPressed;
final IconData? iconDataSuffix;
final bool? enabled;
final bool? expands;
final int? maxLines;
final TextEditingController? controller;
final double? borderRadius;
const CustomForm(
{Key? key,
this.hintText,
this.initialValue,
this.obscureText = false,
this.controller,
this.expands = false,
this.maxLines = 1,
this.borderRadius,
this.enabled,
this.iconData,
this.validator,
this.iconDataSuffix,
this.suffixIconPressed,
this.containerColor,
this.keyboardType,
this.onChanged,
this.iconColor,
this.borderColor})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius!),
color: containerColor,
),
child: Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8),
child: TextFormField(
expands: expands!,
controller: controller,
maxLines: maxLines,
obscureText: obscureText!,
initialValue: initialValue,
enabled: enabled,
validator: validator,
keyboardType: keyboardType,
onChanged: onChanged,
style: Theme.of(context).textTheme.headline5,
decoration: InputDecoration(
enabled: true,
hintText: hintText,
border: InputBorder.none,
hintStyle: Theme.of(context)
.textTheme
.headline5!
.copyWith(color: Colors.grey),
prefixIcon: iconData == null
? null
: Icon(
iconData,
size: 30,
color: iconColor,
),
suffixIcon: iconDataSuffix == null
? null
: IconButton(
onPressed: suffixIconPressed,
icon: Icon(
iconDataSuffix,
color: iconColor,
size: 18,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: borderColor!),
),
),
),
),
);
}
}
|
import React from "react";
import { TableContainer, Table, TableHead, TableBody, TableRow, TableCell, Paper } from "@mui/material";
export const SupermarkeTable = () => {
return (
<TableContainer component={Paper}>
<Table arial-label="simple table">
<TableHead>
<TableRow>
<TableCell>Address</TableCell>
<TableCell>Line</TableCell>
<TableCell>Order Status</TableCell>
<TableCell>Time Order</TableCell>
<TableCell>Duration</TableCell>
</TableRow>
</TableHead>
<TableBody>
{tableData.map((row) => (
<TableRow key={row.address} sx={{ "&:last-child td, &:last-child th": { border: 0 } }}>
<TableCell>{row.address}</TableCell>
<TableCell>{row.line}</TableCell>
<TableCell>{row.order_status}</TableCell>
<TableCell>{row.time_ready}</TableCell>
<TableCell>{row.duration}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
};
const tableData = [
{
address: "MC001",
line: "Main Assy # 1",
order_status: "On Delivery",
time_ready: "30-Aug 14:10",
duration: "20 Min",
},
{
address: "MC002",
line: "Main Assy # 2",
order_status: "Ready",
time_ready: "30-Aug 13:00",
duration: "60 Min",
},
{
address: "MC003",
line: "Main Assy # 3",
order_status: "On Preparing",
time_ready: "30-Aug 13:00",
duration: "60 Min",
},
{
address: "MC004",
line: "Main Assy # 4",
order_status: "Urgent",
time_ready: "30-Aug 13:00",
duration: "60 Min",
},
];
|
package com.example.jsonparsing;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
adapter = new ArrayAdapter(getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "JSON Data is" +
" downloading", Toast.LENGTH_LONG).show();
}
@Override
protected List<HashMap<String, String>> doInBackground(Void... Void) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
List<HashMap<String, String>> contactList = new ArrayList<>();
JSONArray contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
return contactList;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(List<HashMap<String, String>> result) {
super.onPostExecute(result);
if (result != null) {
adapter.add(result);
adapter.notifyDataSetChanged();
}
}
}
}
|
import pandas as pd
import numpy as np
from statistics import linear_regression, correlation
# random forest regressor
# from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
# KNN regressor
from sklearn.neighbors import KNeighborsRegressor
# test train split
from sklearn.model_selection import train_test_split
import pickle
import os
import matplotlib.pyplot as plt
from utils.helpers import get_nearest_lat_lon
### plotting stuff
# change the matplotlib font to use open sans
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'Open Sans'
COLOURS = ['#3F7D20', '#A0DDE6', '#542e71','#3F7CAC','#698F3F']
global project_root_path
project_root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def load_model(bmu, X_train, y_train):
os.makedirs(os.path.join(project_root_path, 'models'), exist_ok=True)
try:
# make a folder for the plots
model_folder = os.path.join(project_root_path, 'models')
if not os.path.exists(model_folder):
os.mkdir(model_folder)
filename = f'{bmu}_model.pkl'
model_path = os.path.join(model_folder, filename)
with open(model_path, 'rb') as f:
model = pickle.load(f)
return model
except Exception as e:
model = KNeighborsRegressor(weights='distance')
model.fit(X_train, y_train)
with open(model_path, 'wb') as f:
pickle.dump(model, f)
return model
class PCEY:
def __init__(self, data_obj, bmu, lat, lon, capacity, name, gen_type):
self.weather_stats_df = data_obj['weather_stats_df']
self.ws_df = data_obj['ws_df']
self.gen_df = data_obj['gen_df']
self.bav_df = data_obj['bav_df']
self.preprocessed_df = None
self.energy_yield_df = None
self.power_curve_df = None
self.month_df = None
self.r2 = None
self.p50_energy_yield = None
self.prediction_ok = False
self.COL_PREDICTED_MONTHLY = 'predicted_monthly_generation_GWh'
self.COL_IDEAL_YIELD = 'ideal_yield_GWh'
self.COL_PREDICTED_IDEAL_YIELD = 'predicted_ideal_yield_GWh'
self.COL_NET_YIELD = 'net_yield_GWh'
self.COL_CURTAILMENT_LOSSES = 'curtailment_losses_GWh'
self.COL_QCd_YIELD = 'combined_yield_GWh'
self.COL_DAILY_PREDICTED = 'average_daily_predicted_yield_GWh'
self.COL_DAILY_IDEAL_YIELD = 'average_daily_ideal_yield_GWh'
self.COL_DAILY_NET_YIELD = 'average_daily_net_yield_GWh'
self.COL_DAILY_QCd_YIELD = 'average_daily_combined_yield_GWh'
self.bmu = bmu
self.lat = lat
self.lon = lon
self.capacity = capacity
self.name = name
self.gen_type = gen_type
self.nearest_lat, self.nearest_lon = get_nearest_lat_lon(self.lat, self.lon)
def get_ml_prediction(self):
prediction_file_path = os.path.join(project_root_path, 'data', 'predictions', f'{self.bmu}.parquet')
os.makedirs(os.path.dirname(prediction_file_path), exist_ok=True)
# unseen data
unseen_file_path = os.path.join(project_root_path, 'data', 'unseen_data', f'{self.bmu}.parquet')
os.makedirs(os.path.dirname(unseen_file_path), exist_ok=True)
if os.path.exists(prediction_file_path):
self.preprocessed_df = pd.read_parquet(prediction_file_path)
self.unseen_df = pd.read_parquet(unseen_file_path)
self.prediction_ok = True
return
try:
if self.preprocessed_df is None:
self._preprocess_data()
# test train split
ml_df = self.preprocessed_df[['wind_speed', 'wind_direction_degrees', self.COL_IDEAL_YIELD]].dropna().copy()
# round the wind direction to the nearest 5
ml_df['wind_direction_degrees'] = ml_df['wind_direction_degrees'].apply(lambda x: round(x/5)*5)
# round the wind speed to the nearest 0.5
ml_df['wind_speed'] = ml_df['wind_speed'].apply(lambda x: round(x*2)/2)
# drop any duplicates
filt = ml_df.duplicated(subset=['wind_speed', 'wind_direction_degrees', self.COL_IDEAL_YIELD], keep='first')
# ideal yield = 0
filt2 = ml_df[self.COL_IDEAL_YIELD] == 0
# count the number of duplicates
n_duplicates = filt.sum()
print('n_duplicates: ', n_duplicates)
# drop the duplicates and where the ideal yield is 0
ml_df = ml_df[~filt & ~filt2]
# any values where the ideal yield is 0, drop them
ml_df = ml_df[ml_df[self.COL_IDEAL_YIELD] != 0]
X = ml_df[['wind_speed', 'wind_direction_degrees']][:-336]
y = ml_df[self.COL_IDEAL_YIELD][:-336]
# validation data
unseen_df = ml_df[['wind_speed', 'wind_direction_degrees', self.COL_IDEAL_YIELD]][-336:].copy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# fit the model
model = load_model(self.bmu, X_train, y_train)
# get the predictions
y_pred = model.predict(X_test)
self.preprocessed_df[self.COL_PREDICTED_IDEAL_YIELD] = np.nan
# where the feature cols are not null, predict the ideal yield
filt = self.preprocessed_df[['wind_speed', 'wind_direction_degrees']].notnull().all(axis=1)
self.preprocessed_df.loc[filt, self.COL_PREDICTED_IDEAL_YIELD] = model.predict(self.preprocessed_df.loc[filt, ['wind_speed', 'wind_direction_degrees']])#
self.prediction_ok = True
# save the file to the data folder
self.preprocessed_df.to_parquet(prediction_file_path)
unseen_df[self.COL_PREDICTED_IDEAL_YIELD] = model.predict(unseen_df[['wind_speed', 'wind_direction_degrees']])
unseen_df = unseen_df.resample('30T').last()
unseen_df.to_parquet(unseen_file_path)
self.unseen_df = unseen_df.copy()
except Exception as e:
print('get_ml_prediction(), error: ', e)
self.prediction_ok = False
def _preprocess_data(self):
# merge bav, gen and weather data
merged_df= self.ws_df[['wind_speed']].resample('30T').last().copy()
merged_df['wind_direction_degrees'] = self.ws_df[['wind_direction_degrees']].resample('30T').last().copy()
merged_df['Quantity (MW)'] = self.gen_df[['Quantity (MW)']].resample('30T').last().copy()
day_gen_df = self.gen_df[['Quantity (MW)']].resample('1D').count()
# merge this and forward fill
merged_df['gen_count'] = day_gen_df.reindex(merged_df.index, method='ffill').copy()
merged_df['gen_count_bool'] = merged_df['gen_count'] >= 48.
merged_df['Total'] = self.bav_df[['Total']].resample('30T').last().fillna(0).copy()
# interpolate the ws_df
for col in ['wind_speed', 'wind_direction_degrees']:
merged_df[col].interpolate(method='linear', inplace=True, limit=2)
merged_df[self.COL_NET_YIELD] = merged_df['Quantity (MW)'] / 2000.
merged_df[self.COL_CURTAILMENT_LOSSES] = -merged_df['Total'] / 1000.
# drop the total column and the quantity column
merged_df.drop(columns=['Total', 'Quantity (MW)'], inplace=True)
# fill the na values with 0
# for col in [self.COL_NET_YIELD, self.COL_CURTAILMENT_LOSSES]:
# merged_df[col].fillna(0., inplace=True, limit_direction='forward')
merged_df[self.COL_IDEAL_YIELD] = merged_df[self.COL_NET_YIELD].fillna(0) + merged_df[self.COL_CURTAILMENT_LOSSES].fillna(0)
# remove the self.col_ideal_yield where 0
# merged_df.loc[merged_df[self.COL_IDEAL_YIELD] == 0, self.COL_IDEAL_YIELD] = np.nan
self.preprocessed_df = merged_df.copy()
def auto_qc(self, month_df):
# Initialize columns
for col in [self.COL_NET_YIELD, self.COL_IDEAL_YIELD]:
month_df[col+'_ok'] = np.nan
month_df[col+'_fail'] = np.nan
# Apply filters
filt = (month_df['data_coverage_%'] >= 60) & (month_df['running_well'])
actual_data_filt = month_df['peak_generation'].notnull()
month_df.loc[filt, self.COL_NET_YIELD+'_ok'] = month_df.loc[filt, self.COL_NET_YIELD]
month_df.loc[filt, self.COL_IDEAL_YIELD+'_ok'] = month_df.loc[filt, self.COL_IDEAL_YIELD]
month_df.loc[~filt, self.COL_NET_YIELD+'_fail'] = month_df.loc[~filt & actual_data_filt, self.COL_NET_YIELD]
month_df.loc[~filt, self.COL_IDEAL_YIELD+'_fail'] = month_df.loc[~filt & actual_data_filt, self.COL_IDEAL_YIELD]
# More QC calculations
month_df[self.COL_QCd_YIELD] = month_df[self.COL_IDEAL_YIELD+'_ok']
month_df.loc[month_df[self.COL_IDEAL_YIELD+'_ok'].isnull(), self.COL_QCd_YIELD] = month_df.loc[month_df[self.COL_IDEAL_YIELD+'_ok'].isnull(), self.COL_PREDICTED_IDEAL_YIELD]
# Divide by the number of days in the month for daily calculations
month_df[self.COL_DAILY_NET_YIELD] = month_df[self.COL_NET_YIELD+'_ok'] / month_df.index.days_in_month
month_df[self.COL_DAILY_IDEAL_YIELD] = month_df[self.COL_IDEAL_YIELD+'_ok'] / month_df.index.days_in_month
month_df[self.COL_DAILY_PREDICTED] = month_df[self.COL_PREDICTED_IDEAL_YIELD] / month_df.index.days_in_month
month_df[self.COL_DAILY_QCd_YIELD] = month_df[self.COL_QCd_YIELD] / month_df.index.days_in_month
# make a combined column of the predicted and actual ideal yield_ok
month_df[self.COL_DAILY_IDEAL_YIELD+'_fail'] = month_df[self.COL_IDEAL_YIELD+'_fail'] / month_df.index.days_in_month
month_df[self.COL_DAILY_NET_YIELD+'_fail'] = month_df[self.COL_NET_YIELD+'_fail'] / month_df.index.days_in_month
month_df[self.COL_DAILY_IDEAL_YIELD+'_ok'] = month_df[self.COL_IDEAL_YIELD+'_ok'] / month_df.index.days_in_month
month_df[self.COL_DAILY_NET_YIELD+'_ok'] = month_df[self.COL_NET_YIELD+'_ok'] / month_df.index.days_in_month
self.month_df = month_df.copy()
def calculate_monthly_df(self):
if ~self.prediction_ok:
self.get_ml_prediction()
_df = self.preprocessed_df.copy()
# Group by month
month_df = _df[[self.COL_NET_YIELD, self.COL_IDEAL_YIELD, self.COL_CURTAILMENT_LOSSES, self.COL_PREDICTED_IDEAL_YIELD]].resample('1MS').sum()
# Calculate the availability for each month
month_df['data_coverage_%'] = _df[self.COL_NET_YIELD].resample('1MS').count() / (month_df.index.days_in_month * 48) * 100.
month_df['peak_generation'] = _df[self.COL_NET_YIELD].resample('1MS').max()
# Get the 90th percentile generation
running_well_val = _df[self.COL_NET_YIELD].quantile(0.85)
month_df['running_well'] = month_df['peak_generation'] >= running_well_val
return month_df
def load_month_df(self):
file_path = os.path.join(project_root_path, 'data', 'pcey_data', f'{self.bmu}_monthly.parquet')
os.makedirs(os.path.dirname(file_path), exist_ok=True)
unseen_file_path = os.path.join(project_root_path, 'data', 'unseen_data', f'{self.bmu}.parquet')
if os.path.exists(file_path):
self.month_df = pd.read_parquet(file_path)
self.unseen_df = pd.read_parquet(unseen_file_path)
else:
# Step 1: Calculate the monthly data frame
monthly_df = self.calculate_monthly_df()
# Step 2: Apply auto quality control
self.auto_qc(monthly_df)
# save the file
self.month_df.to_parquet(file_path)
def _load_fit_dict(self, df):
'''
uses stats.linregress to calculate the r2
compares the predicted ideal yield with the actual ideal yield
this is the _ok column
'''
# drop the na values
_lin_reg_df = df[[self.COL_DAILY_PREDICTED, self.COL_DAILY_IDEAL_YIELD+'_ok']].dropna()
# linear regression between predicted and actual
slope, intercept = linear_regression(_lin_reg_df[self.COL_DAILY_PREDICTED], _lin_reg_df[self.COL_DAILY_IDEAL_YIELD+'_ok'])
r_value = correlation(_lin_reg_df[self.COL_DAILY_PREDICTED], _lin_reg_df[self.COL_DAILY_IDEAL_YIELD+'_ok'])
self.fit_dict = {'slope': slope, 'intercept': intercept, 'r_value': r_value}
self.prediction_r2 = r_value**2
def _calculate_monthly_curtailment_losses(self,df):
'''
This takes in a dataframe with the following columns:
- ideal yield
- measured losses
for the total range, this function calculates the monthly curtailment losses
as a percentage of the ideal yield for each month
'''
# group by month
month_df = df[[self.COL_IDEAL_YIELD, self.COL_CURTAILMENT_LOSSES]].copy()
# group by month and get the median
# calculate the curtailment losses as a percentage of the ideal yield
month_df['curtailment_losses_%'] = month_df[self.COL_CURTAILMENT_LOSSES] / month_df[self.COL_IDEAL_YIELD] * 100.
# group by month number and get the median
month_df['month_number'] = month_df.index.month
month_df = month_df[['curtailment_losses_%', 'month_number']].groupby('month_number').median()
return month_df['curtailment_losses_%']
def _calculate_monthly_energy_yield(self, df):
'''
This takes in a dataframe with the following columns:
- ideal yield
- measured losses
for the total range, this function calculates the monthly curtailment losses
as a percentage of the ideal yield for each month
'''
# group by month
month_df = df[[self.COL_QCd_YIELD]].copy()
# group by month number and get the median
month_df['month_number'] = month_df.index.month
month_df = month_df[[self.COL_QCd_YIELD, 'month_number']].groupby('month_number').median()
return month_df[self.COL_QCd_YIELD]
def calculate_energy_yield(self):
if self.month_df is None:
self.load_month_df()
try:
# merge the two dfs
combined_df = pd.merge(self.weather_stats_df, self.month_df, left_index=True, right_index=True, how='outer')
curtailment_losses = self._calculate_monthly_curtailment_losses(combined_df)
energy_yield = self._calculate_monthly_energy_yield(combined_df)
self._load_fit_dict(combined_df)
# now add the percentage curtailment losses
year_df = pd.DataFrame(index = [1,2,3,4,5,6,7,8,9,10,11,12])
year_df['curtailment_losses_%'] = curtailment_losses
year_df['energy_without_curtailment'] = energy_yield
year_df['energy_with_curtailment'] = (1- curtailment_losses/100.) * energy_yield
year_df['curtailment_losses'] = (curtailment_losses/100.) * energy_yield
year_df['month_number'] = year_df.index
# add the month name
year_df['month_name'] = year_df['month_number'].apply(lambda x: pd.to_datetime(str(x), format='%m').strftime('%B'))
# calculate the ideal yield
self.p50_energy_yield = year_df['energy_with_curtailment'].sum()
self.p50_ideal_yield = year_df['energy_without_curtailment'].sum()
self.losses_due_to_curtailment = year_df['curtailment_losses'].sum()
self.losses_as_percentage = self.losses_due_to_curtailment / self.p50_energy_yield * 100.
self.n_data_points = self.month_df[self.COL_NET_YIELD+'_ok'].count()
self.energy_yield_df = year_df.copy()
except Exception as e:
print('calculate_energy_yield(), error: ', e)
|
//
// ComparableView.swift
// CookBook
//
// Created by km on 06/10/2022.
//
import SwiftUI
struct Userk: Identifiable, Comparable {
let id = UUID()
let firstName: String
let lastName: String
static func <(lhs: Userk, rhs: Userk) -> Bool {
lhs.lastName < rhs.lastName
}
}
struct ComparableView: View {
let users = [
Userk(firstName: "Arnold", lastName: "Rimmer"),
Userk(firstName: "Kristine", lastName: "Kochanski"),
Userk(firstName: "David", lastName: "Lister"),
].sorted {
$0.lastName < $1.lastName
}
var body: some View {
List(users) { user in
Text("\(user.lastName), \(user.firstName)")
}
}
}
struct ComparableView_Previews: PreviewProvider {
static var previews: some View {
ComparableView()
}
}
|
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
if not hasattr(func, 'alltime'):
func.alltime = 0
func.alltime += elapsed_time
print(f"{func.__name__} выполнялась {elapsed_time:.6f} секунд")
print(f"Суммарное время вызовов {func.__name__}: {func.alltime:.6f} секунд")
return result
return wrapper
class ExampleClass:
@timer
def some_method(self):
time.sleep(1)
return "Завершено"
@timer
def test_function():
time.sleep(2)
return "Готово"
if __name__ == "__main__":
ex = ExampleClass()
ex.some_method()
ex.some_method()
test_function()
test_function()
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { shallow } from 'enzyme';
import React from 'react';
import { mockBrowserFields } from '../../containers/source/mock';
import { TestProviders } from '../../mock';
import { DragDropContextWrapper } from './drag_drop_context_wrapper';
import { DroppableWrapper } from './droppable_wrapper';
import { useMountAppended } from '../../utils/use_mount_appended';
jest.mock('../../lib/kibana');
describe('DroppableWrapper', () => {
const mount = useMountAppended();
describe('rendering', () => {
test('it renders against the snapshot', () => {
const message = 'draggable wrapper content';
const wrapper = shallow(
<TestProviders>
<DragDropContextWrapper browserFields={mockBrowserFields}>
<DroppableWrapper droppableId="testing">{message}</DroppableWrapper>
</DragDropContextWrapper>
</TestProviders>
);
expect(wrapper.find('DroppableWrapper')).toMatchSnapshot();
});
test('it renders the children when a render prop is not provided', () => {
const message = 'draggable wrapper content';
const wrapper = mount(
<TestProviders>
<DragDropContextWrapper browserFields={mockBrowserFields}>
<DroppableWrapper droppableId="testing">{message}</DroppableWrapper>
</DragDropContextWrapper>
</TestProviders>
);
expect(wrapper.text()).toEqual(message);
});
test('it does NOT render the children if a render method is provided', () => {
const message = 'draggable wrapper content';
const wrapper = mount(
<TestProviders>
<DragDropContextWrapper browserFields={mockBrowserFields}>
<DroppableWrapper render={() => null} droppableId="testing">
<div data-test-subj="this-should-not-render">{message}</div>
</DroppableWrapper>
</DragDropContextWrapper>
</TestProviders>
);
expect(wrapper.find('[data-test-subj="this-should-not-render"]').exists()).toBe(false);
});
test('it renders the render prop contents when a render prop is provided', () => {
const wrapper = mount(
<TestProviders>
<DragDropContextWrapper browserFields={mockBrowserFields}>
<DroppableWrapper
render={({ isDraggingOver }) => <div>{`isDraggingOver is: ${isDraggingOver}`}</div>}
droppableId="testing"
/>
</DragDropContextWrapper>
</TestProviders>
);
expect(wrapper.text()).toEqual('isDraggingOver is: false');
});
});
});
|
using AOGSystem.Application.General.Query.Model;
using AOGSystem.Application.Sales.Query;
using AOGSystem.Domain.Sales;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace AOGSystem.Application.Sales.Command
{
public class SalesCloserCommandHandler : IRequestHandler<SalesCloserCommand, ReturnDto<SalesQueryModel>>
{
private readonly ISaleRepository _saleRepository;
public SalesCloserCommandHandler(ISaleRepository saleRepository)
{
_saleRepository = saleRepository;
}
public async Task<ReturnDto<SalesQueryModel>> Handle(SalesCloserCommand request, CancellationToken cancellationToken)
{
var model = await _saleRepository.GetSalesByIDAsync(request.Id);
if (model == null)
return new ReturnDto<SalesQueryModel>
{
Data = null,
Count = 0,
IsSuccess = false,
Message = "The Sales order can not be found"
};
model.SetStatus(request.Status);
model.UpdatedAT = DateTime.Now;
model.UpdatedBy = request.UpdatedBy;
var result = await _saleRepository.SaveChangesAsync();
if (result == 0)
return new ReturnDto<SalesQueryModel>
{
Data = null,
Count = 0,
IsSuccess = false,
Message = "Someting went wrong when shipmnet for sales order processed",
};
var returnDate = new SalesQueryModel
{
Id = model.Id,
CompanyId = model.CompanyId,
OrderByName = model.OrderByName,
OrderByEmail = model.OrderByEmail,
OrderNo = model.OrderNo,
CustomerOrderNo = model.CustomerOrderNo,
ShipToAddress = model.ShipToAddress,
Status = model.Status,
IsApproved = model.IsApproved,
Note = model.Note,
IsFullyShipped = model.IsFullyShipped,
AWBNo = model.AWBNo,
ShipDate = model.ShipDate,
ReceivedByCustomer = model.ReceivedByCustomer,
ReceivedDate = model.ReceivedDate,
};
var message = model.Status == "Closed" ? "Loan order closed successfully" : model.Status == "Re-Opened" ? "Loan order re-opened successfully" : "";
return new ReturnDto<SalesQueryModel>
{
Data = returnDate,
Count = 1,
IsSuccess = true,
Message = message
};
}
}
public class SalesCloserCommand : IRequest<ReturnDto<SalesQueryModel>>
{
public Guid Id { get; set; }
public string Status { get; set; }
[JsonIgnore]
public Guid? UpdatedBy { get; private set; }
public void SetUpdatedBy(Guid updatedBy) { UpdatedBy = updatedBy; }
}
}
|
/**
*
*/
package com.flipkart.business;
import java.util.List;
import com.flipkart.bean.Bookings;
import com.flipkart.bean.Gym;
import com.flipkart.bean.User;
/**
* @Author Sugam, Harsh, Ali , Srashti , Dipti
*/
public interface UserServices {
/**
* This method cancels a slot with a given bookingId
* @param slotId
* @return
* @author bhavya.khandelwal, avinash, atulya
*/
boolean cancelSlots(int slotId);
/**
* This method lists all the Bookings with given userId
* @param userId
* @return
* @author bhavya.khandelwal, avinash, atulya
*/
List<Bookings> getAllBookings(String userId);
/**
* This method lists all the Gyms with all the slots available
* @return List<Gym>
* @author bhavya.khandelwal, avinash, atulya
*/
List<Gym> getAllGymsWithSlots();
/**
* This method lists all the Gyms in a particular area
* @param area
* @return List<Gym>
* @author bhavya.khandelwal, avinash, atulya
*/
List<Gym> getAllGymsByArea(String area);
/**
* This method books a slot with given gymId, time and email specific to a user
* @param gymId
* @param time
* @param email
* @return
* @author bhavya.khandelwal, avinash, atulya
*/
boolean bookSlots(int gymId, int time, String email);
/**
* This method validates a User with a given Username and password
* @param username
* @param pass
* @return true if validation succeeds
* @author bhavya.khandelwal, avinash, atulya
*/
boolean validateUser(String username, String pass);
/**
* This method creates a User
* @param user
* @author bhavya.khandelwal, avinash, atulya
*/
void createUser(User user);
public boolean verifyGymUserPassword(String email, String password, String updatedPassword);
/**
* This method verifies a User Password with given email and password
* @param email
* @param password
* @param updatedPassword
* @return
* @author bhavya.khandelwal, avinash, atulya
*/
void updateGymUserPassword(String email, String password, String updatedPassword);
}
|
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Comments } from '../models/comments.model';
import { Post } from '../models/post.model';
import {environment} from '../../environments/environment'
@Injectable({
providedIn:'root'
})
export class PostService {
post$ = new BehaviorSubject<Post[]>([]);
constructor(private http: HttpClient) { }
getAllPosts():Observable<Post[]> { //we get observable whenever an api is called.
return this.http.get<Post[]>(environment.serverUrl +'/posts') ;
}
getCommentsByPostId(postId: number) : Observable<Comments[]>{
return this.http.get<Comments[]>(environment.serverUrl +'/comments?postId='+postId);
}
deletePost(postId: number) :Observable<any>{
return this.http.delete(environment.serverUrl +'/posts/'+postId);
}
insertPost(post: Post) : Observable<Post> {
return this.http.post<Post>(environment.serverUrl +'/posts', post);
}
getPostById(postId: number):Observable<Post> {
return this.http.get<Post>(environment.serverUrl +'/posts/'+postId);
}
editPost(post: Post) : Observable<Post>{
return this.http.put<Post>(environment.serverUrl +'/posts/'+post.id,post );
}
}
|
use std::str::FromStr;
use std::time::Duration;
use duration_str::deserialize_duration;
use reqwest::Method;
use serde::{Deserialize, Serialize, Serializer};
const DEFAULT_SMTP_HOST: &str = "127.0.0.1";
const DEFAULT_SMTP_PORT: u16 = lettre::transport::smtp::SMTP_PORT;
const fn default_smtp_port() -> u16 {
DEFAULT_SMTP_PORT
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
/// Notification methods. Not currently used.
pub notify: Vec<String>,
/// Interval between heartbeats
#[serde(
serialize_with = "serialize_duration",
deserialize_with = "deserialize_duration"
)]
pub heartbeat: Duration,
pub log: LogConfig,
pub http: HttpConfig,
#[cfg(feature = "discord")]
pub discord: DiscordConfig,
#[cfg(feature = "email")]
pub email: MailConfig,
pub watch: Vec<WatchEntry>,
}
impl Default for Config {
fn default() -> Self {
Self {
notify: vec!["email".to_string(), "discord".to_string()],
heartbeat: Duration::from_secs(60 * 10), // 10 minutes
log: LogConfig {
enabled: true,
level: "warn,dominion=info".to_string(),
file: None,
},
http: HttpConfig::default(),
#[cfg(feature = "discord")]
discord: DiscordConfig::default(),
#[cfg(feature = "email")]
email: MailConfig::default(),
watch: vec![
WatchEntry {
protocol: "http".to_string(),
url: "https://example.com".to_string(),
method: Method::GET,
headers: vec![],
interval: Duration::from_secs(30),
variation: 0.25, // 25% - 1h requests will be in the range of 1h-1h15m
stagger: Duration::from_secs(5),
ignore: vec![],
},
WatchEntry {
protocol: "http".to_string(),
url: "https://example2.com".to_string(),
method: Method::GET,
headers: vec![],
interval: Duration::from_secs(60 * 10), // 10 minutes
variation: default_variation(),
stagger: default_stagger(),
ignore: vec![],
},
],
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct LogConfig {
pub enabled: bool,
pub level: String,
pub file: Option<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HttpConfig {
pub user_agent: Option<String>,
}
#[cfg(feature = "discord")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DiscordConfig {
pub enabled: bool,
pub token: String,
#[serde(default)]
pub purge: bool,
#[serde(default)]
pub purge_after: u64,
}
impl Default for DiscordConfig {
fn default() -> Self {
Self {
enabled: false,
token: "".to_string(),
purge: false,
purge_after: 0,
}
}
}
#[cfg(feature = "email")]
#[derive(Debug, Serialize, Deserialize)]
pub struct MailConfig {
pub enabled: bool,
pub smtp_host: String,
#[serde(default = "default_smtp_port")]
pub smtp_port: u16,
pub smtp_use_tls: bool,
#[serde(default)]
pub smtp_username: String,
#[serde(default)]
pub smtp_password: String,
pub from_address: String,
pub to_address: String,
}
#[cfg(feature = "email")]
impl Default for MailConfig {
fn default() -> Self {
Self {
enabled: false,
smtp_host: DEFAULT_SMTP_HOST.to_string(),
smtp_port: DEFAULT_SMTP_PORT,
smtp_use_tls: true,
smtp_username: "".to_string(),
smtp_password: "".to_string(),
from_address: "Dominion <[email protected]>".to_string(),
to_address: "".to_string(),
}
}
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct WatchEntry {
#[serde(default = "default_protocol", skip_serializing_if = "skip_protocol")]
pub protocol: String,
// HTTP params
pub url: String,
#[serde(
default = "default_method",
skip_serializing_if = "skip_method",
serialize_with = "serialize_method",
deserialize_with = "deserialize_method"
)]
pub method: Method,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub headers: Vec<String>,
#[serde(
serialize_with = "serialize_duration",
deserialize_with = "deserialize_duration"
)]
pub interval: Duration,
/// Variation in time, in percentage, between requests.
#[serde(default = "default_variation", skip_serializing_if = "skip_variation")]
pub variation: f32,
/// Initial requests will be staggered a random amount between 0s and this value.
#[serde(
default = "default_stagger",
skip_serializing_if = "skip_stagger",
serialize_with = "serialize_duration",
deserialize_with = "deserialize_duration"
)]
pub stagger: Duration,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ignore: Vec<String>,
}
fn default_protocol() -> String {
"http".to_string()
}
fn skip_protocol(value: &String) -> bool {
value.is_empty() || value == &default_protocol()
}
fn default_method() -> Method {
Method::GET
}
fn skip_method(value: &Method) -> bool {
value == default_method()
}
fn serialize_method<S>(value: &Method, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(value.to_string().as_str())
}
struct MethodDeserializer;
impl<'de> serde::de::Visitor<'de> for MethodDeserializer {
type Value = Method;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("expected string, e.g. 'GET'")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let duration = Method::from_str(s).map_err(serde::de::Error::custom)?;
Ok(duration)
}
}
pub fn deserialize_method<'de, D>(deserializer: D) -> Result<Method, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(MethodDeserializer)
}
fn default_variation() -> f32 {
0.0
}
fn skip_variation(value: &f32) -> bool {
*value == default_variation()
}
fn default_stagger() -> Duration {
Duration::from_secs(0)
}
fn skip_stagger(value: &Duration) -> bool {
value.as_secs_f32() == default_stagger().as_secs_f32()
}
pub fn format_duration(value: &Duration) -> String {
const SECS_IN_MINUTE: u64 = 60;
const SECS_IN_HOUR: u64 = SECS_IN_MINUTE * 60;
const SECS_IN_DAY: u64 = SECS_IN_HOUR * 24;
const SECS_IN_WEEK: u64 = SECS_IN_DAY * 7;
const SECS_IN_MONTH: u64 = SECS_IN_DAY * 30;
const SECS_IN_YEAR: u64 = SECS_IN_MONTH * 12;
const NANOS_IN_MICRO: u32 = 1000;
const NANOS_IN_MILLI: u32 = NANOS_IN_MICRO * 1000;
let mut secs = value.as_secs();
let mut nanos = value.subsec_nanos();
let mut str = String::new();
if secs >= SECS_IN_YEAR {
let years = secs / SECS_IN_YEAR;
secs -= years * SECS_IN_YEAR;
str.push_str(format!("{years}y").as_str());
}
if secs >= SECS_IN_MONTH {
let months = secs / SECS_IN_MONTH;
secs -= months * SECS_IN_MONTH;
str.push_str(format!("{months}mon").as_str());
}
if secs >= SECS_IN_WEEK {
let weeks = secs / SECS_IN_WEEK;
secs -= weeks * SECS_IN_WEEK;
str.push_str(format!("{weeks}w").as_str());
}
if secs >= SECS_IN_DAY {
let days = secs / SECS_IN_DAY;
secs -= days * SECS_IN_DAY;
str.push_str(format!("{days}d").as_str());
}
if secs >= SECS_IN_HOUR {
let hours = secs / SECS_IN_HOUR;
secs -= hours * SECS_IN_HOUR;
str.push_str(format!("{hours}h").as_str());
}
if secs >= SECS_IN_MINUTE {
let mins = secs / SECS_IN_MINUTE;
secs -= mins * SECS_IN_MINUTE;
str.push_str(format!("{mins}m").as_str());
}
if secs > 0 {
str.push_str(format!("{secs}s").as_str());
}
if nanos >= NANOS_IN_MILLI {
let millis = nanos / NANOS_IN_MILLI;
nanos -= millis * NANOS_IN_MILLI;
str.push_str(format!("{millis}ms").as_str());
}
if nanos >= NANOS_IN_MICRO {
let micros = nanos / NANOS_IN_MICRO;
nanos -= micros * NANOS_IN_MICRO;
str.push_str(format!("{micros}us").as_str());
}
if nanos > 0 {
str.push_str(format!("{nanos}ns").as_str());
}
str
}
fn serialize_duration<S>(value: &Duration, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let str = format_duration(value);
s.serialize_str(str.as_str())
}
|
import { BrowserRouter, Route, Routes } from "react-router-dom";
import "./App.scss";
import Menu from "./components/Menu/Menu";
import UpcomingTasks from "./Pages/Upcoming-tasks/UpcomingTasks";
import TodayTasks from "./Pages/Today-tasks/TodayTasks";
import Calendar from "./Pages/Calendar/Calendar";
import StickyWall from "./Pages/Sticky-wall/StickyWall";
import ErrorPage from "./Pages/Error-page/ErrorPage";
import ListPage from "./Pages/List-page/ListPage";
import TagPage from "./Pages/Tag-page/TagPage";
function App() {
return (
<BrowserRouter>
<div className="wrapper">
<Menu />
<div className="main">
<Routes>
<Route path="/" element={<TodayTasks />} />
<Route path="upcoming" element={<UpcomingTasks />} />
<Route path="today" element={<TodayTasks />} />
<Route path="calendar" element={<Calendar />} />
<Route path="sticky-wall" element={<StickyWall />} />
<Route path="*" element={<ErrorPage />} />
<Route path="/list/:title" element={<ListPage />} />
<Route path="/tags/:title" element={<TagPage />} />
</Routes>
</div>
</div>
</BrowserRouter>
);
}
export default App;
|
package com.controller;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;
import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;
/**
* 组团活动报名
* 后端接口
* @author
* @email
*/
@RestController
@Controller
@RequestMapping("/huodongOrder")
public class HuodongOrderController {
private static final Logger logger = LoggerFactory.getLogger(HuodongOrderController.class);
@Autowired
private HuodongOrderService huodongOrderService;
@Autowired
private TokenService tokenService;
@Autowired
private DictionaryService dictionaryService;
//级联表service
@Autowired
private HuodongService huodongService;
@Autowired
private YonghuService yonghuService;
/**
* 后端列表
*/
@RequestMapping("/page")
public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
String role = String.valueOf(request.getSession().getAttribute("role"));
if(false)
return R.error(511,"永不会进入");
else if("用户".equals(role))
params.put("yonghuId",request.getSession().getAttribute("userId"));
else if("活动管理员".equals(role))
params.put("huodongguanliyuanId",request.getSession().getAttribute("userId"));
if(params.get("orderBy")==null || params.get("orderBy")==""){
params.put("orderBy","id");
}
PageUtils page = huodongOrderService.queryPage(params);
//字典表数据转换
List<HuodongOrderView> list =(List<HuodongOrderView>)page.getList();
for(HuodongOrderView c:list){
//修改对应字典表字段
dictionaryService.dictionaryConvert(c, request);
}
return R.ok().put("data", page);
}
/**
* 后端详情
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id, HttpServletRequest request){
logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
HuodongOrderEntity huodongOrder = huodongOrderService.selectById(id);
if(huodongOrder !=null){
//entity转view
HuodongOrderView view = new HuodongOrderView();
BeanUtils.copyProperties( huodongOrder , view );//把实体数据重构到view中
//级联表
HuodongEntity huodong = huodongService.selectById(huodongOrder.getHuodongId());
if(huodong != null){
BeanUtils.copyProperties( huodong , view ,new String[]{ "id", "createTime", "insertTime", "updateTime"});//把级联的数据添加到view中,并排除id和创建时间字段
view.setHuodongId(huodong.getId());
}
//级联表
YonghuEntity yonghu = yonghuService.selectById(huodongOrder.getYonghuId());
if(yonghu != null){
BeanUtils.copyProperties( yonghu , view ,new String[]{ "id", "createTime", "insertTime", "updateTime"});//把级联的数据添加到view中,并排除id和创建时间字段
view.setYonghuId(yonghu.getId());
}
//修改对应字典表字段
dictionaryService.dictionaryConvert(view, request);
return R.ok().put("data", view);
}else {
return R.error(511,"查不到数据");
}
}
/**
* 后端保存
*/
@RequestMapping("/save")
public R save(@RequestBody HuodongOrderEntity huodongOrder, HttpServletRequest request){
logger.debug("save方法:,,Controller:{},,huodongOrder:{}",this.getClass().getName(),huodongOrder.toString());
String role = String.valueOf(request.getSession().getAttribute("role"));
if(false)
return R.error(511,"永远不会进入");
else if("组团活动".equals(role))
huodongOrder.setHuodongId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));
else if("用户".equals(role))
huodongOrder.setYonghuId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));
huodongOrder.setInsertTime(new Date());
huodongOrder.setCreateTime(new Date());
huodongOrderService.insert(huodongOrder);
return R.ok();
}
/**
* 后端修改
*/
@RequestMapping("/update")
public R update(@RequestBody HuodongOrderEntity huodongOrder, HttpServletRequest request){
logger.debug("update方法:,,Controller:{},,huodongOrder:{}",this.getClass().getName(),huodongOrder.toString());
String role = String.valueOf(request.getSession().getAttribute("role"));
// if(false)
// return R.error(511,"永远不会进入");
// else if("组团活动".equals(role))
// huodongOrder.setHuodongId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));
// else if("用户".equals(role))
// huodongOrder.setYonghuId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));
//根据字段查询是否有相同数据
Wrapper<HuodongOrderEntity> queryWrapper = new EntityWrapper<HuodongOrderEntity>()
.eq("id",0)
;
logger.info("sql语句:"+queryWrapper.getSqlSegment());
HuodongOrderEntity huodongOrderEntity = huodongOrderService.selectOne(queryWrapper);
if(huodongOrderEntity==null){
huodongOrderService.updateById(huodongOrder);//根据id更新
return R.ok();
}else {
return R.error(511,"表中有相同数据");
}
}
/**
* 审核
*/
@RequestMapping("/shenhe")
public R shenhe(@RequestBody HuodongOrderEntity huodongOrderEntity, HttpServletRequest request){
logger.debug("shenhe方法:,,Controller:{},,huodongOrderEntity:{}",this.getClass().getName(),huodongOrderEntity.toString());
if(huodongOrderEntity.getHuodongOrderYesnoTypes() == 2){//通过
HuodongOrderEntity huodongOrder = huodongOrderService.selectById(huodongOrderEntity.getId());
HuodongEntity huodongEntity = huodongService.selectById(huodongOrder.getHuodongId());
List<HuodongOrderEntity> huodongOrderEntities = huodongOrderService.selectList(new EntityWrapper<HuodongOrderEntity>()
.eq("huodong_id", huodongOrder.getHuodongId())
.eq("huodong_order_yesno_types", 2)
);
if(huodongOrderEntities.size()>=huodongEntity.getHuodongZuidaNumber()){
return R.error(511,"该组团活动参与人数已满,无法审核通过");
}
}else if(huodongOrderEntity.getHuodongOrderYesnoTypes() == 3){//拒绝
}
huodongOrderEntity.setHuodongOrderShenheTime(new Date());//审核时间
huodongOrderService.updateById(huodongOrderEntity);//审核
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Integer[] ids){
logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
huodongOrderService.deleteBatchIds(Arrays.asList(ids));
return R.ok();
}
/**
* 批量上传
*/
@RequestMapping("/batchInsert")
public R save( String fileName, HttpServletRequest request){
logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
Integer yonghuId = Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId")));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
List<HuodongOrderEntity> huodongOrderList = new ArrayList<>();//上传的东西
Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
Date date = new Date();
int lastIndexOf = fileName.lastIndexOf(".");
if(lastIndexOf == -1){
return R.error(511,"该文件没有后缀");
}else{
String suffix = fileName.substring(lastIndexOf);
if(!".xls".equals(suffix)){
return R.error(511,"只支持后缀为xls的excel文件");
}else{
URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
File file = new File(resource.getFile());
if(!file.exists()){
return R.error(511,"找不到上传文件,请联系管理员");
}else{
List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
dataList.remove(0);//删除第一行,因为第一行是提示
for(List<String> data:dataList){
//循环
HuodongOrderEntity huodongOrderEntity = new HuodongOrderEntity();
// huodongOrderEntity.setHuodongOrderUuidNumber(data.get(0)); //申请编号 要改的
// huodongOrderEntity.setHuodongId(Integer.valueOf(data.get(0))); //组团活动 要改的
// huodongOrderEntity.setYonghuId(Integer.valueOf(data.get(0))); //用户 要改的
// huodongOrderEntity.setLianxirenName(data.get(0)); //联系人姓名 要改的
// huodongOrderEntity.setLianxirenPhone(data.get(0)); //联系人手机号 要改的
// huodongOrderEntity.setHuodongOrderContent("");//详情和图片
// huodongOrderEntity.setInsertTime(date);//时间
// huodongOrderEntity.setHuodongOrderYesnoTypes(Integer.valueOf(data.get(0))); //报名状态 要改的
// huodongOrderEntity.setHuodongOrderYesnoText(data.get(0)); //审核意见 要改的
// huodongOrderEntity.setHuodongOrderShenheTime(sdf.parse(data.get(0))); //审核时间 要改的
// huodongOrderEntity.setCreateTime(date);//时间
huodongOrderList.add(huodongOrderEntity);
//把要查询是否重复的字段放入map中
//申请编号
if(seachFields.containsKey("huodongOrderUuidNumber")){
List<String> huodongOrderUuidNumber = seachFields.get("huodongOrderUuidNumber");
huodongOrderUuidNumber.add(data.get(0));//要改的
}else{
List<String> huodongOrderUuidNumber = new ArrayList<>();
huodongOrderUuidNumber.add(data.get(0));//要改的
seachFields.put("huodongOrderUuidNumber",huodongOrderUuidNumber);
}
}
//查询是否重复
//申请编号
List<HuodongOrderEntity> huodongOrderEntities_huodongOrderUuidNumber = huodongOrderService.selectList(new EntityWrapper<HuodongOrderEntity>().in("huodong_order_uuid_number", seachFields.get("huodongOrderUuidNumber")));
if(huodongOrderEntities_huodongOrderUuidNumber.size() >0 ){
ArrayList<String> repeatFields = new ArrayList<>();
for(HuodongOrderEntity s:huodongOrderEntities_huodongOrderUuidNumber){
repeatFields.add(s.getHuodongOrderUuidNumber());
}
return R.error(511,"数据库的该表中的 [申请编号] 字段已经存在 存在数据为:"+repeatFields.toString());
}
huodongOrderService.insertBatch(huodongOrderList);
return R.ok();
}
}
}
}catch (Exception e){
e.printStackTrace();
return R.error(511,"批量插入数据异常,请联系管理员");
}
}
/**
* 前端列表
*/
@IgnoreAuth
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params, HttpServletRequest request){
logger.debug("list方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
// 没有指定排序字段就默认id倒序
if(StringUtil.isEmpty(String.valueOf(params.get("orderBy")))){
params.put("orderBy","id");
}
PageUtils page = huodongOrderService.queryPage(params);
//字典表数据转换
List<HuodongOrderView> list =(List<HuodongOrderView>)page.getList();
for(HuodongOrderView c:list)
dictionaryService.dictionaryConvert(c, request); //修改对应字典表字段
return R.ok().put("data", page);
}
/**
* 前端详情
*/
@RequestMapping("/detail/{id}")
public R detail(@PathVariable("id") Long id, HttpServletRequest request){
logger.debug("detail方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
HuodongOrderEntity huodongOrder = huodongOrderService.selectById(id);
if(huodongOrder !=null){
//entity转view
HuodongOrderView view = new HuodongOrderView();
BeanUtils.copyProperties( huodongOrder , view );//把实体数据重构到view中
//级联表
HuodongEntity huodong = huodongService.selectById(huodongOrder.getHuodongId());
if(huodong != null){
BeanUtils.copyProperties( huodong , view ,new String[]{ "id", "createDate"});//把级联的数据添加到view中,并排除id和创建时间字段
view.setHuodongId(huodong.getId());
}
//级联表
YonghuEntity yonghu = yonghuService.selectById(huodongOrder.getYonghuId());
if(yonghu != null){
BeanUtils.copyProperties( yonghu , view ,new String[]{ "id", "createDate"});//把级联的数据添加到view中,并排除id和创建时间字段
view.setYonghuId(yonghu.getId());
}
//修改对应字典表字段
dictionaryService.dictionaryConvert(view, request);
return R.ok().put("data", view);
}else {
return R.error(511,"查不到数据");
}
}
/**
* 前端保存
*/
@RequestMapping("/add")
public R add(@RequestBody HuodongOrderEntity huodongOrder, HttpServletRequest request){
logger.debug("add方法:,,Controller:{},,huodongOrder:{}",this.getClass().getName(),huodongOrder.toString());
HuodongEntity huodongEntity = huodongService.selectById(huodongOrder.getHuodongId());
if(huodongEntity == null){
return R.error(511,"查不到该组团活动");
}
List<HuodongOrderEntity> huodongOrderEntities = huodongOrderService.selectList(new EntityWrapper<HuodongOrderEntity>()
.eq("huodong_id", huodongOrder.getHuodongId())
.eq("huodong_order_yesno_types", 2)
);
HuodongOrderEntity huodongOrderEntity = huodongOrderService.selectOne(new EntityWrapper<HuodongOrderEntity>()
.eq("huodong_id", huodongOrder.getHuodongId())
.notIn("huodong_order_yesno_types", 3)
);
if(huodongOrderEntity != null){
if(huodongOrderEntity.getHuodongOrderYesnoTypes()==1)
return R.error("您已经报名过当前组团活动了,请等待审核哦");
if(huodongOrderEntity.getHuodongOrderYesnoTypes()==2)
return R.error("您已经报名过当前组团活动了,已经审核通过了,无需重复报名");
}
if(huodongOrderEntities.size()>=huodongEntity.getHuodongZuidaNumber()){
return R.error(511,"该组团活动参与人数已满,请去查看其他组团活动吧");
}
Integer userId = (Integer) request.getSession().getAttribute("userId");
huodongOrder.setYonghuId(userId); //设置订单支付人id
huodongOrder.setHuodongOrderUuidNumber(String.valueOf(new Date().getTime()));
huodongOrder.setHuodongOrderYesnoTypes(1);
huodongOrder.setInsertTime(new Date());
huodongOrder.setCreateTime(new Date());
huodongOrderService.insert(huodongOrder);//新增订单
return R.ok();
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stopwatch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="stopwatch">
<h1 id="displayTime">00:00:00</h1>
<div class="buttons">
<img src="images/stop.png" onclick="watchStop()">
<img src="images/start.png" onclick="watchStart()">
<img src="images/reset.png" onclick="watchReset()">
</div>
</div>
<script>
let [seconds, minutes, hours] = [0, 0, 0];
let displayTime = document.getElementById("displayTime");
let timer = null;
function stopwatch(){
seconds++;
if(seconds == 60){
seconds=0;
minutes++;
if(minutes == 60){
minutes = 0;
hours++
}
}
let h = hours < 10 ? "0" + hours : hours;
let m = minutes < 10 ? "0" + minutes : minutes;
let s = seconds < 10 ? "0" + seconds : seconds;
displayTime.innerHTML = h + ":" + m + ":" + s;
}
function watchStart(){
if(timer =! null){
clearInterval(timer);
}
timer = setInterval(stopwatch,1000);
}
function watchStop(){
clearInterval(timer);
}
function watchReset(){
clearInterval(timer);
seconds = 0;
minutes = 0;
hours = 0;
displayTime.innerHTML = "00:00:00";
}
</script>
</body>
</html>
|
package com.example.lab11_letanhung_2001210520;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText edtName, edtAge;
User selectedUser = null;
Button btnInsert, btnDelete, btnUpdate;
ListView lvKq;
ArrayList<User>lsUser = new ArrayList<>();
ArrayList<String>lsDataLV = new ArrayList<>();
ArrayAdapter<String>adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addControls();
FirebaseApp.initializeApp(this);
// initData();
getDataFromFirebase();
adapter=new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1,lsDataLV);
lvKq.setAdapter(adapter);
addEvent();
}
ArrayList<String> convertToArrString(ArrayList<User> lsUs)
{
ArrayList<String>lsString=new ArrayList<>();
for (User u:lsUs ) {
String s = "Tên: " + u.getName() + " - " + "Tuổi: "+String.valueOf(u.getAge());
lsString.add(s);
}
return lsString;
}
public void addControls()
{
edtName=(EditText) findViewById(R.id.edtName);
edtAge=(EditText) findViewById(R.id.edtAge);
btnInsert = (Button) findViewById(R.id.btnInsert);
btnDelete=(Button) findViewById(R.id.btnDelete);
btnUpdate=(Button) findViewById(R.id.btnUpdate);
lvKq = (ListView) findViewById(R.id.lvKq);
}
public void addEvent() {
// Thiết lập sự kiện khi nhấn nút Insert
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("User");
User u = new User(edtName.getText().toString(), Integer.parseInt(edtAge.getText().toString()));
String key = myRef.push().getKey();
myRef.child("User" +(lsUser.size()+1)).setValue(u);
}
});
// Thiết lập sự kiện khi nhấn nút Delete
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedUser != null) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("User");
// Tạo truy vấn để tìm và xóa người dùng được chọn
Query query = myRef.orderByChild("name").equalTo(selectedUser.getName());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
if (userSnapshot.child("age").getValue(Integer.class).equals(selectedUser.getAge())) {
userSnapshot.getRef().removeValue();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Xử lý lỗi nếu có
}
});
}
}
});
// Thiết lập sự kiện khi nhấn nút Update
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedUser != null) {
// Lấy dữ liệu mới từ các EditText
String newName = edtName.getText().toString();
int newAge = Integer.parseInt(edtAge.getText().toString());
// Cập nhật dữ liệu trong Firebase
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("User");
Query query = myRef.orderByChild("name").equalTo(selectedUser.getName());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
if (userSnapshot.child("age").getValue(Integer.class).equals(selectedUser.getAge())) {
// Cập nhật dữ liệu
userSnapshot.getRef().child("name").setValue(newName);
userSnapshot.getRef().child("age").setValue(newAge);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
});
lvKq.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Lưu trữ thông tin của mục được chọn
selectedUser = lsUser.get(position);
// Hiển thị thông tin của mục được chọn lên các EditText
edtName.setText(selectedUser.getName());
edtAge.setText(String.valueOf(selectedUser.getAge()));
}
});
}
public void initData()
{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("User");
for(int i=0;i<5; i++) {
User user = new User("Ten " + i, 15+i);
myRef.child("User_" +i).setValue(user);//thêm push để tạo mục có key random, ko bị đè khi bị trùng
}
}
public void getDataFromFirebase ()
{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("User");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
lsUser.clear();
for (DataSnapshot userSnapshot: snapshot.getChildren()) {
User user = userSnapshot.getValue(User.class);
lsUser.add(user);
}
lsDataLV = convertToArrString(lsUser);
adapter=new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1,lsDataLV);
lvKq.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
|
/**
* Common database helper functions.
*/
class DBHelper {
constructor() {
this.dbPromise = null;
}
/**
* Database URL.
* Change this to restaurants.json file location on your server.
*/
static get DATABASE_URL() {
const port = 1337 // Change this to your server port
return `http://localhost:${port}/restaurants`;
}
static openDB() {
if(this.dbPromise) {
return this.dbPromise;
} else {
this.dbPromise = idb.open('restaurant_review', 2, upgradeDb => {
let store = upgradeDb.createObjectStore('restaurants', {
keyPath: 'id'
});
let store2 = upgradeDb.createObjectStore('restaurant', {
keyPath: 'id'
});
store.createIndex('id', 'id');
store2.createIndex('id', 'id');
})
return this.dbPromise;
}
}
/**
* Fetch all restaurants.
*/
static fetchRestaurants(callback) {
this.openDB().then(db => {
console.log(db);
let tx = db.transaction('restaurants');
return tx.objectStore('restaurants').getAll();
}).then(restaurants => {
console.log('index db got -->', restaurants);
if(restaurants.length === 0) {
//fetch restaurants
console.log('from internet');
let xhr = new XMLHttpRequest();
xhr.open('GET', DBHelper.DATABASE_URL);
xhr.onload = () => {
if (xhr.status === 200) { // Got a success response from server!
// console.log("**************", xhr.responseText)
const json = JSON.parse(xhr.responseText);
console.log(json);
// const restaurants = json.restaurants;
callback(null, json);
//store for future as well
this.openDB().then(db => {
if(!db) return;
let tx = db.transaction('restaurants', 'readwrite');
let store = tx.objectStore('restaurants');
json.forEach(restaurant=> {
store.put(restaurant);
})
return tx.complete;
}).then(function() { // successfully added restaurants to IndexDB
console.log("Restaurants added to Index DB successfully")
}).catch(function(error) { // failed adding restaurants to IndexDB
console.log(error)
})
} else { // Oops!. Got an error from server.
const error = (`Request failed. Returned status of ${xhr.status}`);
callback(error, null);
}
};
xhr.send();
} else {
console.log('from idb');
callback(null, restaurants);
}
})
}
/**
* Fetch a restaurant by its ID.
*/
static fetchRestaurantById(id, callback) {
// fetch all restaurants with proper error handling.
this.openDB().then(db => {
let tx = db.transaction('restaurant');
let store = tx.objectStore('restaurant');
return store.get(parseInt(id));
}).then(restaurant => {
console.log('index db got -->', restaurant);
if(restaurant) {
console.log('from index db')
callback(null, restaurant);
} else {
console.log('from internet')
let xhr = new XMLHttpRequest();
xhr.open('GET', DBHelper.DATABASE_URL + `/${id}`);
xhr.onload = () => {
if(xhr.status === 200) {
if(xhr.responseText !== "") {
const restaurant = JSON.parse(xhr.responseText);
callback(null, restaurant);
this.openDB().then(db => {
if(!db) return
let tx = db.transaction('restaurant', 'readwrite');
let store = tx.objectStore('restaurant');
store.put(restaurant);
})
} else {
callback('Restaurant does not exist', null);
}
} else {
const error = (`Request failed. Returned status of ${xhr.status}`);
callback(error, null);
}
};
xhr.send();
}
});
// DBHelper.fetchRestaurantByIdXhr((error, restaurant) => {
// if (error) {
// callback(error, null);
// } else {
// const restaurant = restaurants.find(r => r.id == id);
// if (restaurant) { // Got the restaurant
// callback(null, restaurant);
// } else { // Restaurant does not exist in the database
// callback('Restaurant does not exist', null);
// }
// }
// });
}
static manageCaches() {
setInterval(() => {
// delete indexDB cache regularly to get new data
console.log('clearing cache')
DBHelper.deleteRestaurantsCache();
DBHelper.deleteRestaurantCache();
}, 60 * 30 * 1000);
}
static deleteRestaurantsCache() {
this.openDB().then(db => {
if(!db) return;
let tx = db.transaction('restaurants', 'readwrite');
let store = tx.objectStore('restaurants');
return store.openCursor();
}).then(function deleteRestaurants(cursor) {
if(!cursor) return;
cursor.delete();
return cursor.continue().then(deleteRestaurants);
}).then(() => {
console.log(' Restaurants cache cleared');
})
}
static deleteRestaurantCache() {
this.openDB().then(db => {
if(!db) return;
let tx = db.transaction('restaurant', 'readwrite');
let store = tx.objectStore('restaurant');
return store.openCursor();
}).then(function deleteRestaurant(cursor) {
if(!cursor) return;
cursor.delete();
return cursor.continue().then(deleteRestaurant);
}).then(() => {
console.log(' Restaurant cache cleared');
})
}
/**
* Fetch restaurants by a cuisine type with proper error handling.
*/
static fetchRestaurantByCuisine(cuisine, callback) {
// Fetch all restaurants with proper error handling
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Filter restaurants to have only given cuisine type
const results = restaurants.filter(r => r.cuisine_type == cuisine);
callback(null, results);
}
});
}
/**
* Fetch restaurants by a neighborhood with proper error handling.
*/
static fetchRestaurantByNeighborhood(neighborhood, callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Filter restaurants to have only given neighborhood
const results = restaurants.filter(r => r.neighborhood == neighborhood);
callback(null, results);
}
});
}
/**
* Fetch restaurants by a cuisine and a neighborhood with proper error handling.
*/
static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
let results = restaurants
if (cuisine != 'all') { // filter by cuisine
results = results.filter(r => r.cuisine_type == cuisine);
}
if (neighborhood != 'all') { // filter by neighborhood
results = results.filter(r => r.neighborhood == neighborhood);
}
callback(null, results);
}
});
}
/**
* Fetch all neighborhoods with proper error handling.
*/
static fetchNeighborhoods(callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Get all neighborhoods from all restaurants
const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)
// Remove duplicates from neighborhoods
const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)
callback(null, uniqueNeighborhoods);
}
});
}
/**
* Fetch all cuisines with proper error handling.
*/
static fetchCuisines(callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Get all cuisines from all restaurants
const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)
// Remove duplicates from cuisines
const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)
callback(null, uniqueCuisines);
}
});
}
/**
* Restaurant page URL.
*/
static urlForRestaurant(restaurant) {
return (`./restaurant.html?id=${restaurant.id}`);
}
/**
* Restaurant image URL.
*/
static imageUrlForRestaurant(restaurant) {
return (`../images/${restaurant.photograph}`);
}
/**
* Map marker for a restaurant.
*/
static mapMarkerForRestaurant(restaurant, map) {
// https://leafletjs.com/reference-1.3.0.html#marker
const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],
{title: restaurant.name,
alt: restaurant.name,
url: DBHelper.urlForRestaurant(restaurant)
})
marker.addTo(newMap);
return marker;
}
/* static mapMarkerForRestaurant(restaurant, map) {
const marker = new google.maps.Marker({
position: restaurant.latlng,
title: restaurant.name,
url: DBHelper.urlForRestaurant(restaurant),
map: map,
animation: google.maps.Animation.DROP}
);
return marker;
} */
}
|
import React from 'react';
import { Formik } from 'formik';
import * as Yup from 'yup';
import { Movie, MovieFormView, MovieInput, MovieInputSize } from 'components';
import { MOVIE_FORM } from 'utils';
interface IMovieForm {
headline: string;
movie: Movie;
onSubmit: (movieItem: Movie) => void;
}
const SignupSchema = Yup.object().shape({
title: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Required'),
voteAverage: Yup.number()
.min(0, 'Less then min value!')
.max(10, 'More then max value!')
.required('Required'),
posterPath: Yup.string().required('Required'),
runtime: Yup.number().min(0, 'Too low!').required('Required'),
releaseDate: Yup.string().required('Required'),
genres: Yup.array().min(1, 'Less then min value!').required('Required'),
overview: Yup.string().required('Required')
});
export const MovieForm = ({ onSubmit, headline, movie }: IMovieForm) => {
const filterInputsBySize = (inputSize: MovieInputSize) => {
return MOVIE_FORM.filter(({ size }) => size === inputSize).map(formItem => (
<MovieInput key={formItem.keyName} {...formItem} />
));
};
return (
<Formik
initialValues={movie}
validationSchema={SignupSchema}
onSubmit={values => {
onSubmit(values);
}}
>
{({ handleSubmit, handleReset }) => (
<MovieFormView
smallInputs={filterInputsBySize(MovieInputSize.SMALL)}
largeInputs={filterInputsBySize(MovieInputSize.LARGE)}
headline={headline}
handleReset={handleReset}
handleSubmit={handleSubmit}
/>
)}
</Formik>
);
};
|
//Weakly Typed language(No explict type assignments like bool,num,int,etc)
//Object Oriented Language
//Semicolon is not required in js but you can use it
//To run on terminal we can use node js (JS Runtime Environment) eg-> node basics.js
// PRINT STATEMENT
console.log("Hello World")
console.log("Hello","Wolrd") //Hello World
// DATA TYPES
//String, Number, Boolean, Undefined, Null, Bigint, Symbol, Object(Object,Array,Date)
//Assignment using var,let or const only
//var can be assigned to any dtype and used in whole program
var myName = "Vasu Somani"
yourName = "Anonymous";//Works
console.log(typeof(you))
//let is similar to var but limited to the scope you defined in
let ourName = "Nothing"
//const values can't be changed (Use all CAPITALS)
const PI = 3.14
// uninitalized
var a;
console.log(a); //Will give undefined
// OPERATORS
// + - / * %
// ++ --
// += -= *= /=
// > >= < <=
// == != (3=="3" is ture) Equalitiy Operator
// === !== (3==="3" is false) Strict Equaltiy Opeartor
// && (and) || (or)
// STRINGS
// ' ' and " " for declaration
var myName = "Vasu Somani"
// ` ` Using backticks for interpolation in strings
console.log(`Hola mi soy ${myName}`)
console.log("Hola mi soy ${myName}") // Wont work in "" or ''
// .length to find length of string
var n = myName.length
// indexing
var subString = myName[0]
// immutable
myName[2] = "k" //Won't work and won't give error too
myName = "Vaku Somani" //Will work
// ARRAYS
// Declaration
var arr = ["2", 3, 4, 5.9]
// muttable
arr[0] = 10
//Below functions will work even if the array is declared as const
// add at end
arr.push("9")
// add at begin
arr.unshift(20)
// remove at end
var poppedEnd = arr.pop()
// remove at begin
var poppedBegin = arr.shift()
// copying array
const arr1 = [1, 2, 3, 4]
let arr2
arr2 = arr1 //copy by refrence
console.log("arr2 before:", arr1)
arr1[0] = "xyz" //arr2 will also change
console.log("arr2 after:",arr2)
const arr3 = [1, 2, 3, 4]
let arr4
arr4 = [...arr3] //copy by value //using spread operator
arr3[0] = "xyz" //arr4 won't change
console.log(arr4)
let arr5 = arr3.slice() //copying using slice method
arr3[0] = "0" //arr5 wont change
console.log(arr5)
//for each loop in array
for (var x of arr3) {
console.log(x)
}
//map in array
arr3.map((i)=>console.log(i+" YO"))
// SWITCH
var choice = 'a'
switch (choice) {
case 'a':
console.log("A it is");
break;
case 'b':
console.log("B it is");
break;
default:
console.log("Dont know");
break;
}
// "use strict"
// Literal Expression
// To indicate that the code should be executed in "strict mode".
// In Strict Mode you cannot use undeclared vaiables
// Declared by adding "use strict" to the beginning of a script or function
t1 = 3.14; // Works
myFunction();
function myFunction() {
"use strict";
// t2 = 3.14; // Error
}
// Deleting a variable, object or function is not allowed.
/*
"use strict";
let x = 3.14;
delete x; // Error
/*
//In strict mode, eval() can not declare a variable using the var keyword
/*
"use strict";
eval("var x = 2");
alert(x); //Error
*/
|
<!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>William Shakespeare</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<header>
<nav>
<ul>
<li>
<a href="#">Writers</a>
</li>
<li>
<a href="#">Discusions</a>
</li>
<li>
<a href="#">Books</a>
</li>
<li>
<a href="#">The authors</a>
</li>
<li>
<a href="#">Readers</a>
</li>
</ul>
</nav>
</header>
<div class="block">
<main>
<article>
<h1>William Shakespeare</h1>
<hr>
<p>From Wikipedia, the free encyclopedia</p>
<p>
William Shakespeare (bapt. 26 April 1564 – 23 April 1616) was an English poet, playwright and actor, widely regarded as the greatest writer in the English language and the world's greatest dramatist. He is often called England's national poet and the "Bard of Avon". His extant works, including collaborations, consist of approximately 39 plays, 154 sonnets, two long narrative poems, and a few other verses, some of uncertain authorship. His plays have been translated into every major living language and are performed more often than those of any other playwright.
</p>
<p>
Shakespeare was born and raised in Stratford-upon-Avon, Warwickshire. At the age of 18, he married Anne Hathaway, with whom he had three children: Susanna and twins Hamnet and Judith. Sometime between 1585 and 1592, he began a successful career in London as an actor, writer, and part-owner of a playing company called the Lord Chamberlain's Men, later known as the King's Men. At age 49 (around 1613), he appears to have retired to Stratford, where he died three years later. Few records of Shakespeare's private life survive; this has stimulated considerable speculation about such matters as his physical appearance, his sexuality, his religious beliefs, and whether the works attributed to him were written by others. Such theories are often criticised for failing to adequately note that few records survive of most commoners of the period.
</p>
<p>
Shakespeare produced most of his known works between 1589 and 1613. His early plays were primarily comedies and histories and are regarded as some of the best work produced in these genres. Until about 1608, he wrote mainly tragedies, among them Hamlet, Othello, King Lear, and Macbeth, all considered to be among the finest works in the English language. In the last phase of his life, he wrote tragicomedies (also known as romances) and collaborated with other playwrights.
</p>
<p>
Many of Shakespeare's plays were published in editions of varying quality and accuracy in his lifetime. However, in 1623, two fellow actors and friends of Shakespeare's, John Heminges and Henry Condell, published a more definitive text known as the First Folio, a posthumous collected edition of Shakespeare's dramatic works that included all but two of his plays. The volume was prefaced with a poem by Ben Jonson, in which Jonson presciently hails Shakespeare in a now-famous quote as "not of an age, but for all time".
</p>
<p>
Throughout the 20th and 21st centuries, Shakespeare's works have been continually adapted and rediscovered by new movements in scholarship and performance. His plays remain popular and are studied, performed, and reinterpreted through various cultural and political contexts around the world.
</p>
</article>
<h2>Similar authors:</h2>
<ul>
<li>
<figure>
<img src="images/Anne_Hathaway.jpg" alt="Anne Hathaway">
<figcaption><a href="#">Anne Hathaway</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="images/Dickens_Gurney.jpg" alt="Charles Dickens">
<figcaption><a href="#">Charles Dickens</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="images/Oscar_Wilde_Sarony.jpg" alt="Oscar Wilde">
<figcaption><a href="#">Oscar Wilde</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="images/Cervantes_Jauregui.jpg" alt="Miguel de Cervantes">
<figcaption><a href="#">Miguel de Cervantes</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="images/Edgar_Allan_Poe.jpg" alt="Edgar Allan Poe">
<figcaption><a href="#">Edgar Allan Poe</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="images/WilliamWordsworth.jpg" alt="William Wordsworth">
<figcaption><a href="#">William Wordsworth</a></figcaption>
</figure>
</li>
</ul>
</main>
<aside>
<img src="images/Shakespeare.jpg" alt="William Shakespeare">
<p><strong>Born</strong> 26 April 1564</p>
<p><strong>Died</strong> 23 April 1616</p>
<p><strong>Spouse</strong> Anne Hathaway (m. 1582)</p>
<p>
<strong>Children</strong>
Susanna Hall<br>
Hamnet Shakespeare<br>
Judith Quiney
</p>
<p>
<strong>Parents</strong>
John Shakespeare (father)<br>
Mary Arden (mother)
</p>
</aside>
</div>
</div>
</body>
</html>
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
std::pmr::map<MessageType, QString> MessageTypeMap = {
{Connection, "Connection"},
{Disconnection, "Disconnection"},
{Text, "Text"},
{FileInfo, "FileInfo"},
{FileData, "FileData"}
};
MainWindow::MainWindow(QTcpSocket *socket, QString clientName, QWidget *parent)
: QWidget(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("Chat Application");
this->socket = socket;
this->clientName = clientName;
connect(ui->attachFileButton, &QPushButton::clicked, this, &MainWindow::on_action_attachFileButton_clicked);
connect(ui->sendButton, &QPushButton::clicked, this, &MainWindow::on_action_sendButton_clicked);
model = new QStandardItemModel();
ui->clientList->setModel(model);
addNewClientToUI(clientName);
sendData(MessageType::Connection, clientName.toUtf8());
}
MainWindow::~MainWindow()
{
qDebug() << "MainWindow destroyed";
delete ui;
}
void MainWindow::addNewClientToUI(QString clientName)
{
model->appendRow(new QStandardItem(clientName));
}
void MainWindow::deleteClientFromUI(QString clientName)
{
for(int i = 0; i < model->rowCount(); i++)
{
if(model->item(i)->text() == clientName)
{
model->removeRow(i);
break;
}
}
}
void MainWindow::sendData(MessageType type, QByteArray data)
{
if(socket)
{
if(socket->isOpen())
{
QByteArray header;
header.prepend(("Type:" + MessageTypeMap[type] + "\0").toUtf8());
header.resize(HEADER_SIZE);
data.prepend(header);
QDataStream stream(socket);
stream.setVersion(QDataStream::Qt_6_7);
stream << data;
}
else
{
QMessageBox::critical(this, "Error", "Could not connect to server");
}
}
else
{
QMessageBox::critical(this, "Error", "Could not connect to server");
}
}
void MainWindow::on_action_attachFileButton_clicked()
{
}
void MainWindow::on_action_sendButton_clicked()
{
QString message = ui->messageInputText->text();
if(!message.isEmpty())
{
message.prepend(clientName + "> ");
sendData(MessageType::Text, message.toUtf8());
ui->chatDialogText->append(message);
ui->messageInputText->clear();
}
}
void MainWindow::readDataFromSocket()
{
if(socket)
{
if(socket->isOpen())
{
QByteArray DataBuffer;
QDataStream stream(socket);
stream.setVersion(QDataStream::Qt_6_7);
stream >> DataBuffer;
QString header = DataBuffer.mid(0, HEADER_SIZE);
QString type = header.split(":")[1].split('\0')[0];
QString data = DataBuffer.mid(HEADER_SIZE);
if(type == MessageTypeMap[Text])
{
ui->chatDialogText->append(data);
}
else if(type == MessageTypeMap[Connection])
{
addNewClientToUI(data);
}
else if(type == MessageTypeMap[Disconnection])
{
deleteClientFromUI(data);
}
}
else
{
QMessageBox::critical(this, "Error", "Could not connect to server");
}
}
else
{
QMessageBox::critical(this, "Error", "Could not connect to server");
}
}
|
/*
* Copyright (c) 2022-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef RENDER_SERVICE_CLIENT_CORE_PIPELINE_RS_SURFACE_HANDLER_H
#define RENDER_SERVICE_CLIENT_CORE_PIPELINE_RS_SURFACE_HANDLER_H
#include <atomic>
#include "common/rs_common_def.h"
#include "common/rs_macros.h"
#ifndef ROSEN_CROSS_PLATFORM
#include <surface.h>
#include "sync_fence.h"
#endif
namespace OHOS {
namespace Rosen {
class RSB_EXPORT RSSurfaceHandler {
public:
// indicates which node this handler belongs to.
explicit RSSurfaceHandler(NodeId id) : id_(id) {}
virtual ~RSSurfaceHandler() noexcept = default;
struct SurfaceBufferEntry {
void Reset()
{
#ifndef ROSEN_CROSS_PLATFORM
buffer = nullptr;
acquireFence = SyncFence::INVALID_FENCE;
releaseFence = SyncFence::INVALID_FENCE;
damageRect = Rect {0, 0, 0, 0};
#endif
timestamp = 0;
}
#ifndef ROSEN_CROSS_PLATFORM
sptr<SurfaceBuffer> buffer;
sptr<SyncFence> acquireFence = SyncFence::INVALID_FENCE;
sptr<SyncFence> releaseFence = SyncFence::INVALID_FENCE;
Rect damageRect = {0, 0, 0, 0};
#endif
int64_t timestamp = 0;
};
void IncreaseAvailableBuffer();
int32_t ReduceAvailableBuffer();
NodeId GetNodeId() const
{
return id_;
}
void SetDefaultWidthAndHeight(int32_t width, int32_t height)
{
#ifndef ROSEN_CROSS_PLATFORM
if (consumer_ != nullptr) {
consumer_->SetDefaultWidthAndHeight(width, height);
}
#endif
}
#ifndef ROSEN_CROSS_PLATFORM
void SetConsumer(const sptr<Surface>& consumer);
const sptr<Surface>& GetConsumer() const
{
return consumer_;
}
void SetBuffer(
const sptr<SurfaceBuffer>& buffer,
const sptr<SyncFence>& acquireFence,
const Rect& damage,
const int64_t timestamp)
{
preBuffer_ = buffer_;
buffer_.buffer = buffer;
buffer_.acquireFence = acquireFence;
buffer_.damageRect = damage;
buffer_.timestamp = timestamp;
}
const sptr<SurfaceBuffer>& GetBuffer() const
{
return buffer_.buffer;
}
const sptr<SyncFence>& GetAcquireFence() const
{
return buffer_.acquireFence;
}
const Rect& GetDamageRegion() const
{
return buffer_.damageRect;
}
void SetReleaseFence(sptr<SyncFence> fence)
{
// The fence which get from hdi is preBuffer's releaseFence now.
preBuffer_.releaseFence = std::move(fence);
}
#endif
SurfaceBufferEntry& GetPreBuffer()
{
return preBuffer_;
}
int32_t GetAvailableBufferCount() const
{
return bufferAvailableCount_;
}
int64_t GetTimestamp() const
{
return buffer_.timestamp;
}
void CleanCache()
{
buffer_.Reset();
preBuffer_.Reset();
}
void ResetBufferAvailableCount()
{
bufferAvailableCount_ = 0;
}
void SetGlobalZOrder(float globalZOrder);
float GetGlobalZOrder() const;
bool HasConsumer() const
{
#ifndef ROSEN_CROSS_PLATFORM
return consumer_ != nullptr;
#else
return false;
#endif
}
inline bool IsCurrentFrameBufferConsumed()
{
return isCurrentFrameBufferConsumed_;
}
inline void ResetCurrentFrameBufferConsumed()
{
isCurrentFrameBufferConsumed_ = false;
}
inline void SetCurrentFrameBufferConsumed()
{
isCurrentFrameBufferConsumed_ = true;
}
protected:
#ifndef ROSEN_CROSS_PLATFORM
sptr<Surface> consumer_;
#endif
private:
NodeId id_ = 0;
SurfaceBufferEntry buffer_;
SurfaceBufferEntry preBuffer_;
float globalZOrder_ = 0.0f;
std::atomic<int> bufferAvailableCount_ = 0;
bool isCurrentFrameBufferConsumed_ = false;
};
}
}
#endif // RENDER_SERVICE_CLIENT_CORE_PIPELINE_RS_SURFACE_HANDLER_H
|
<template>
<el-aside width="200px">
<el-scrollbar>
<el-menu :default-active="route.fullPath" class="el-menu-vertical-demo" style="height:100vh;" :router="true">
<template v-for="data in dataList" :key="data.path">
<el-sub-menu :index="data.path" v-if="data.children.length && checkAuth(data.path)">
<template #title>
<el-icon>
<component :is="mapIcons[data.icon]"></component>
</el-icon>
<span>{{ data.title }}</span>
</template>
<template v-for="item in data.children" :key="item.path">
<el-menu-item :index="item.path" v-if="checkAuth(item.path)">
<el-icon>
<component :is="mapIcons[item.icon]"></component>
</el-icon>
<span>{{ item.title }}</span>
</el-menu-item>
</template>
</el-sub-menu>
<el-menu-item :index="data.path" v-else-if="checkAuth(data.path)">
<el-icon>
<component :is="mapIcons[data.icon]"></component>
</el-icon>
<span>{{ data.title }}</span>
</el-menu-item>
</template>
</el-menu>
</el-scrollbar>
</el-aside>
</template>
<script setup>
import {
Document,
Menu as IconMenu,
Location,
Setting,
HomeFilled,
User,
Key,
OfficeBuilding,
UploadFilled,
List
} from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
import { useUserStore } from '../../store/useUserStore'
import request from '../../util/request';
// 获取路由
const route = useRoute()
// 生命周期
onMounted(() => {
getList()
})
// 获取列表
const dataList = ref([])
const getList = () => {
// 获取列表
request.get('/adminapi/rights').then(res => {
// console.log(res);
dataList.value = res
// console.log(dataList.value);
})
}
// 菜单图标
const mapIcons = {
HomeFilled,
User,
Key,
OfficeBuilding,
UploadFilled,
List
}
const { user } = useUserStore() // 获取用户信息
// 权限控制
const checkAuth = (path) => {
return user.roles.rights.includes(path)
}
</script>
|
import { Injectable } from "@angular/core";
import { Action } from "@ngrx/store";
import { Actions, Effect, ofType } from "@ngrx/effects";
import { Observable, of } from 'rxjs';
import { mergeMap, map, catchError } from 'rxjs/operators';
import { Message } from '../../models';
import { MessageService } from '../services';
import * as messageActions from './message.actions';
@Injectable()
export class MessageEffects {
constructor(
private messageService: MessageService,
private actions$: Actions
) {}
@Effect()
loadMessages$: Observable<Action> = this.actions$.pipe(
ofType(messageActions.MessageActionTypes.Load),
mergeMap(action =>
this.messageService.all().pipe(
map((messages: Message[]) => (new messageActions.LoadSuccess(messages))),
catchError(err => of(new messageActions.LoadFail(err)))
)
)
);
@Effect()
createMessage$: Observable<Action> = this.actions$.pipe(
ofType(messageActions.MessageActionTypes.Create),
map((action: messageActions.Create) => action.payload),
mergeMap((message: Message) =>
this.messageService.create(message).pipe(
map((messages: Message) => (new messageActions.CreateSuccess(message))),
catchError(err => of(new messageActions.CreateFail(err)))
)
)
)
}
|
BeaconReceiver
This app is part of an iBeacon demonstration of Swipe.
The other part consists of the Sender app, also available in the Swipe Github account.
Usage
====
For this demonstration to work you'll need two iOS 7 devices that support Bluetooth 4.0: iPhone 4S and later, iPad 3 and later, iPod touch 5th gen and later.
* Download both the Receiver (this repo) and [Sender](https://github.com/swipestudio/BeaconSender) apps
* Use ´uuidgen´ in OS X Terminal to create a unique UUID
* Change the variable _uuidString in each app's view controller (there is just one) to the UUID you've created
* Install each app on its own iOS device
* Make sure to activate Bluetooth on both devices
* Start the sender app and toggle the activate switch. You'll need to start the Receiver app before it can recognize regions. Keep the receiver device at a reasonable distance from the sender device, or you'll see the welcome screen immediately.
* Have fun with beacons
You can also uncomment the UILabel _meterLabel in the SBRViewController, which will then display the approximate distance to the beacon. The label is not shown by default.
How it works
=========
The sender advertises a CLBeaconRegion with the specified UUID. If the device running the receiver app enters the region matching this UUID (and the app is not in the foreground) it will show a notification to the user, asking them to bring the app to the foreground. When in the foreground, the app constantly checks the distance to the first beacon in the region, and displays an appropriate image if a certain distance is reached (1.5 meters and 3 meters, respectively).
License
=====
Copyright (c) 2013 Swipe GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AxiosError } from 'axios';
import { IAddSkills, IPosition, ISkill } from '../../interfaces';
import { positionService } from '../../services';
interface IPositionState {
positions: IPosition[];
position: IPosition | null;
totalCount: number;
error: null;
deleteSkillError: null;
positionSkills: ISkill[];
}
const initialState: IPositionState = {
positions: [],
position: null,
totalCount: 0,
error: null,
deleteSkillError: null,
positionSkills: []
}
export const getAllPosition = createAsyncThunk<IPosition[] | void>(
'positionSlice/getAllPosition',
async (_, {dispatch, rejectWithValue}) => {
try {
await positionService.getAll(9, 1).then(data => {
dispatch(setPositions({positions: data.rows}));
dispatch(setTotalCount({totalCount: data.count}));
});
} catch (e) {
const err = e as AxiosError;
return rejectWithValue(err.response?.data);
}
}
)
export const getAllWithParamsPosition = createAsyncThunk<IPosition[] | void, {limit: number, page: number}>(
'positionSlice/getAllWithParamsPosition',
async (data, {dispatch, rejectWithValue}) => {
try {
await positionService.getAll(data.limit, data.page).then(data => {
dispatch(setPositions({positions: data.rows}));
dispatch(setTotalCount({totalCount: data.count}));
});
} catch (e) {
const err = e as AxiosError;
return rejectWithValue(err.response?.data);
}
}
)
export const createPosition = createAsyncThunk<void, IPosition>(
'positionSlice/createPosition',
async (position, {dispatch, rejectWithValue}) => {
try {
await positionService.createPosition(position).then(data => {
dispatch(addPosition({position: data}));
dispatch(setPosition({position: data}));
if (data) {
dispatch(setPositionError(null));
}
})
} catch (e) {
const err = e as AxiosError;
return rejectWithValue(err.response?.data);
}
}
)
export const addSkills = createAsyncThunk<void, IAddSkills>(
'positionSlice/addSkills',
async (data, {dispatch, rejectWithValue}) => {
try {
await positionService.addSkills(data.id, data.skill).then(data => {
dispatch(addSkillToPosition({skill: data}));
if (data) {
dispatch(setPositionError(null));
}
})
} catch (e) {
const err = e as AxiosError;
return rejectWithValue(err.response?.data);
}
}
)
export const deleteSkills = createAsyncThunk<void, IAddSkills>(
'positionSlice/deleteSkills',
async (data, {dispatch, rejectWithValue}) => {
try {
await positionService.deleteSkills(data.id, data.skill.id);
dispatch(deleteSkillToPosition({skill: data.skill}));
} catch (e) {
const err = e as AxiosError;
return rejectWithValue(err.response?.data);
}
}
)
const positionSlice = createSlice({
name: 'positionSlice',
initialState,
reducers: {
setPositions: (state, action: PayloadAction<{ positions: IPosition[]}>) => {
state.positions = action.payload.positions;
},
setPosition: (state, action: PayloadAction<{position: IPosition}>) => {
state.position = action.payload.position;
},
addPosition: (state, action: PayloadAction<{position: IPosition}>) => {
state.positions.push(action.payload.position);
},
setPositionError: (state, action) => {
state.error = action.payload;
},
// setAddSkillToPositionError: (state, action) => {
// state.addSkillError = action.payload;
// },
addSkillToPosition: (state, action: PayloadAction<{skill: ISkill}>) => {
state.position?.skills.push(action.payload.skill);
state.positionSkills.push(action.payload.skill);
},
deleteSkillToPosition: (state, action: PayloadAction<{skill: ISkill}>) => {
state.positionSkills = state.positionSkills.filter(skill => skill.id !== action.payload.skill.id);
},
setTotalCount: (state, action: PayloadAction<{totalCount: number}>) => {
state.totalCount = action.payload.totalCount;
},
setPositionSkills: (state, action: PayloadAction<[]>) => {
state.positionSkills = action.payload;
}
},
extraReducers: builder =>
builder
.addCase(createPosition.rejected, (state, action) => {
// @ts-ignore
state.error = action.payload.message;
})
.addCase(addSkills.rejected, (state, action) => {
// @ts-ignore
state.error = action.payload.message;
})
.addCase(deleteSkills.rejected, (state, action) => {
// @ts-ignore
state.deleteSkillError = action.payload.message;
})
})
const positionReducer = positionSlice.reducer;
export default positionReducer;
export const {
setPositions,
setPosition,
addPosition,
setPositionError,
addSkillToPosition,
setTotalCount,
deleteSkillToPosition,
setPositionSkills
} = positionSlice.actions;
|
package com.blogspot.ostas.leetcode.all.medium.count_the_number_of_square_free_subsets;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SolutionTest {
/*
Example 1:
Input: nums = [3,4,4,5]
Output: 3
Explanation: There are 3 square-free subsets in this example:
- The subset consisting of the 0th element [3]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element [5]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements [3,5]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
Example 2:
Input: nums = [1]
Output: 1
Explanation: There is 1 square-free subset in this example:
- The subset consisting of the 0th element [1]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 30
*/
@Test
void example_0() {
var solution = new Solution();
int[] nums = new int[]{3, 4, 4, 5};
int expected = 3;
var result = solution.squareFreeSubsets(nums);
assertThat(result).isEqualTo(expected);
}
@Test
void example_1() {
var solution = new Solution();
int[] nums = new int[]{1};
int expected = 1;
var result = solution.squareFreeSubsets(nums);
assertThat(result).isEqualTo(expected);
}
}
|
var express = require('express');
var router = express.Router();
var User = require('../models/User');
var Category = require('../models/Category');
var Content = require('../models/Content');
router.use(function(req,res,next){
if(!req.userInfo.isAdmin){
//如果当前用户是非管理员
res.send("对不起,只有管理员才可以进入后台管理");
return;
}
next();
});
//首页
router.get('/',function(req,res,next){
res.render('admin/index',{
userInfo: req.userInfo
});
});
//用户管理
router.get('/user',function(req,res){
/*从数据库中读取所有的数据
limit(Number):限制数据条数
skip(2):忽略数据的条数,例子中是2
每页显示两条
1:1-2 skip(0) -> (当前页-1)*limit
2:3-4 skip(2)
*/
var page = Number(req.query.page) || 1;
var limit = 5;
var pages = 0;
//借用方法看数据库中有多少条数据
User.count().then(function(count){
//计算总页数
pages = Math.ceil(count/limit); //向上取整
//取值不能超过pages
page = Math.min(page,pages);
//取值不能小于1
page = Math.max(page,1);
//动态计算
var skip = (page - 1) * limit;
//查询限制
User.find().limit(limit).skip(skip).then(function(users){
res.render('admin/user_index',{
userInfo: req.userInfo,
users: users,
count:count,
pages:pages,
limit:limit,
page:page
});
});
});
});
//分类首页
router.get('/category',function(req,res){
var page = Number(req.query.page) || 1;
var limit = 5;
var pages = 0;
//借用方法看数据库中有多少条数据
Category.count().then(function(count){
//计算总页数
pages = Math.ceil(count/limit); //向上取整
//取值不能超过pages
page = Math.min(page,pages);
//取值不能小于1
page = Math.max(page,1);
//动态计算
var skip = (page - 1) * limit;
//查询限制
Category.find().sort({_id: -1}).limit(limit).skip(skip).then(function(categories){
res.render('admin/category_index',{
userInfo: req.userInfo,
categories: categories,
count:count,
pages:pages,
limit:limit,
page:page
});
});
});
})
//分类的添加
router.get('/category/add',function(req,res){
res.render('admin/category_add',{
userInfo: req.userInfo
})
})
//分类的保存
router.post('/category/add',function(req,res){
var name = req.body.name;
if(name == ''){
res.render('admin/error',{
userInfo: req.userInfo,
message: '名称不能为空'
});
return;
}
//数据库中是否存在同名分类名称
Category.findOne({
name: name
}).then(function(rs){
if(rs){
//数据库中已经存在该分类
res.render('admin/error',{
userInfo:req.userInfo,
message: '分类已经存在'
});
return Promise.reject(); //不执行后面的then()方法
}else{
//数据库中不存在该分类,可以保存
return new Category({
name: name
}).save();
}
}).then(function(newCategory){
res.render('admin/success',{
userInfo: req.userInfo,
message: '分类保存成功',
url:'/admin/category'
});
})
})
//分类的修改
router.get('/category/edit',function(req,res){
//读取要修改的分类的信息,并且用表单的形式展示出来
var id = req.query.id || '';
//获取要修改的分类信息
Category.findOne({
_id: id
}).then(function(category){
if(!category){
res.render('admin/error',{
userInfo: req.userInfo,
message: '分类信息不存在'
});
return Promise.reject();
}else{
res.render('admin/category_edit',{
userInfo: req.userInfo,
category:category
});
}
});
});
//分类信息的保存
router.post('/category/edit',function(req,res){
var id = req.query.id || '';
var name = req.body.name || '';
Category.findOne({
_id: id
}).then(function(category){
//如果该信息id不存在
if(!category){
res.render('admin/error',{
userInfo:req.userInfo,
message: '分类信息存在'
});
return Promise.reject(); //不执行后面的then()方法
}else{
//当前用户没有做任何修改
if(name == category.name){
res.render('admin/success',{
userInfo:req.userInfo,
message: '修改成功',
url:'/admin/category'
});
return Promise.reject();
}else{
//要修改的分类名称是否已经在数据库中存在
return Category.findOne({
_id:{$ne: id},
name: name
})
}
}
}).then(function(sameCategory){
if(sameCategory){
res.render('admin/success',{
userInfo: userInfo,
message: '数据库中已经存在同名分类'
});
}else{
return Category.update({
_id: id
},{
name: name
})
}
}).then(function(){
res.render('admin/success',{
userInfo:req.userInfo,
message:'修改成功',
url: '/admin/category'
})
})
});
//分类的删除
router.get('/category/delete',function(req,res){
var id = req.query.id || '';
Category.remove({
_id:id
}).then(function(){
res.render('admin/success',{
userInfo:req.userInfo,
message:'删除成功',
url: '/admin/category'
})
})
});
//内容首页
router.get('/content',function(req,res){
var page = Number(req.query.page || 1);
var limit = 5;
var pages = 0;
Content.count().then(function(count){
pages = Math.ceil(count/limit);
//取值不能大于总页数
page = Math.min(page,pages);
//取值不能小于1
page = Math.max(page,1);
var skip = (page - 1)*limit;
Content.find().limit(limit).skip(skip).populate(['category', 'user']).sort({addTime: -1}).then(function(content){
// console.log(content);
res.render('admin/content_index',{
userInfo: req.userInfo,
content: content,
count: count,
limit: limit,
page: page,
pages: pages
})
});
})
})
//内容添加
router.get('/content/add',function(req,res){
Category.find().sort({_id: -1}).then(function(categories){
res.render('admin/content_add',{
userInfo:req.userInfo,
categories: categories
});
});
})
//内容保存
router.post('/content/add',function(req,res){
if(req.body.category == ''){
res.render('admin/error',{
userInfo:req.userInfo,
message: '内容分类不能为空'
});
return;
}
if(req.body.title == ''){
res.render('admin/error',{
userInfo:req.userInfo,
message: '内容标题不能为空'
});
return;
}
//保存数据到数据库
new Content({
category: req.body.category,
title: req.body.title,
user: req.userInfo._id.toString(),
description: req.body.description,
content: req.body.content
}).save().then(function(rs) {
res.render('admin/success', {
userInfo: req.userInfo,
message: '内容保存成功',
url: '/admin/content'
})
});
})
//内容的修改
router.get('/content/edit',function(req,res){
var id = req.query.id || '';
var categories = [];
Category.find().sort({_id: -1}).then(function(rs){
categories = rs;
return Content.findOne({
_id: id
}).populate('category');
}).then(function(content){
if(!content){
res.render('admin/error',{
userInfo: req.userInfo,
message: '指定内容不存在'
})
return Promise.reject();
}else{
res.render('admin/content_edit',{
userInfo: req.userInfo,
categories: categories,
content: content
})
}
})
})
//内容的保存
router.post('/content/edit',function(req,res){
var id = req.query.id || '';
if(req.body.category == ''){
res.render('admin/error',{
userInfo:req.userInfo,
message: '内容分类不能为空'
});
return;
}
if(req.body.title == ''){
res.render('admin/error',{
userInfo:req.userInfo,
message: '内容标题不能为空'
});
return;
}
Content.update({
_id: id
},{
category: req.body.category,
title: req.body.title,
description: req.body.description,
content: req.body.content
}).then(function(){
res.render('admin/success',{
userInfo: req.userInfo,
message: '内容保存成功',
url: '/admin/content'
})
})
})
//内容的删除
router.get('/content/delete',function(req,res){
var id = req.query.id || '';
Content.remove({
_id: id
}).then(function(){
res.render('admin/success',{
userInfo: req.userInfo,
message: '删除成功',
url: '/admin/content'
})
})
})
module.exports = router;
|
# Copyright 2020 Alexey Alexandrov <[email protected]>
import numpy as np
from prettytable import PrettyTable
# Вероятность "везения" для критерия Гурвица.
ALPHA = 0.5
def OutMatrix(matrix: np.array):
table = PrettyTable()
table.field_names = ["Стратегии"] + [f"b{j}" for j in range(1, matrix.shape[1] + 1)]
for i in range(matrix.shape[0]):
table.add_row([f"a{i + 1}"] + list(matrix[i]))
return table
def BernulliCriteria(matrix: np.array):
"""
Криетрий недостаточного основания (Бернулли).
:param matrix: матрица стратегий.
:return полученная оптимальная стратегия.
"""
table = OutMatrix(matrix)
col_sum = np.sum(matrix, axis=1)
table.add_column("Ψᵢ", list(col_sum / matrix.shape[1]))
optimal_strategy = f"a{col_sum.argmax(axis=0) + 1}"
print(f"1) Криетрий недостаточного основания Бернулли.\n"
f"Если пользоваться критетрием Бернулли, то следует руководствоваться стратегией {optimal_strategy}.\n"
f"Соответствующее математическое ожидание выигрыша при этом"
f"максимально и равно {col_sum.max(axis=0) / matrix.shape[1]}.\n{table}")
return optimal_strategy
def ValdCriteria(matrix: np.array):
"""
Криетрий пессимизма (Вальда).
:param matrix: матрица стратегий.
:return полученная оптимальная стратегия.
"""
table = OutMatrix(matrix)
col_min = np.min(matrix, axis=1)
table.add_column("αᵢ", list(col_min))
optimal_strategy = f"a{col_min.argmax(axis=0) + 1}"
print(f"2) Криетрий пессимизма Вальда.\n"
f"Пессимистическая стратегия (Вальда) определяет выбор {optimal_strategy} "
f"(нижняя цена игры равна {col_min.max(axis=0)}).\n{table}")
return optimal_strategy
def OptimismCriteria(matrix: np.array):
"""
Криетрий авантюры (максимума, оптимизма).
:param matrix: матрица стратегий.
:return полученная оптимальная стратегия.
"""
optimal_strategy = f"a{np.max(matrix, axis=1).argmax() + 1}"
print(f"3) Критерий авантюры(максимума, оптимизма).\n "
f"Оптимистическая стратегия соответствует выбору {optimal_strategy} "
f"c максимальным выигрышем в матрице - {matrix.max()}.")
return optimal_strategy
def GurvitzCriteria(matrix: np.array):
"""
Криетрий Гурвица.
:param matrix: матрица стратегий.
:return полученная оптимальная стратегия.
"""
table = OutMatrix(matrix)
psi = ALPHA * np.min(matrix, axis=1) + (1 - ALPHA) * np.max(matrix, axis=1)
table.add_column("Ψ", psi)
optimal_strategy = f"a{psi.argmax() + 1}"
print(f"4) Криетрий Гурвица.\n"
f"α = {ALPHA}\n{table}\nНаилучшая стратегия {optimal_strategy}\n"
f"Ожидаемый выигрыш: {psi.max()}")
return optimal_strategy
def SevigeCriteria(matrix: np.array):
"""
Криетрий рисков Севиджа.
:param matrix: матрица стратегий.
:return полученная оптимальная стратегия.
"""
risks = np.max(matrix, axis=0) - matrix
table = OutMatrix(risks)
max_col = np.max(risks, axis=1)
table.add_column("αᵢ", max_col)
optimal_strategy = f"a{max_col.argmin() + 1}"
print(f"5) Критерий Севиджа.\n"
f"Составим таблицу рисков стратегий:\n{table}\n"
f"Таким образом, оптимальная рисковая стратегия - {optimal_strategy}.")
return optimal_strategy
def ChooseBestStrategy(matrix: np.array):
"""
Отбирает наилучшую стратегию согласно принципу большинства на основе всех рассмотренных критериев.
:param matrix: матрица стратегий.
"""
result_map = {}
for k in [f"a{i + 1}" for i in range(matrix.shape[0])]:
result_map[k] = 0
result_map[BernulliCriteria(matrix)] += 1
result_map[ValdCriteria(matrix)] += 1
result_map[OptimismCriteria(matrix)] += 1
result_map[GurvitzCriteria(matrix)] += 1
result_map[SevigeCriteria(matrix)] += 1
strategies = list(result_map.keys())
ranks = list(result_map.values())
table = PrettyTable()
table.field_names = strategies
table.add_row(ranks)
print(f"\nВ итоге выберем стратегию, которая оказалась оптимальной в большем числе критериев:\n{table}\n"
f"По принципу большинства рекомендуем стратегию {strategies[max(enumerate(ranks), key=lambda x: x[1])[0]]}")
|
<?php
/**
* @file
* Configuration pages for CRM Core Data Import.
*/
/**
* Page callback for data import dashboard.
*/
function crm_core_data_import_dashboard_form($form, &$form_state) {
$items = array();
$available = _crm_core_data_import_get_tasks();
crm_core_ui_ctools_add_dropbutton_files();
foreach ($available as $key => $importer) {
$importer = crm_core_data_import_load_importer($key);
// Operations.
$links = array();
$links[] = l(t('Edit source'), 'admin/structure/crm-core/data-import/' . $key . '/source-selection');
$links[] = l(t('Edit source settings'), 'admin/structure/crm-core/data-import/' . $key . '/source-settings');
if (!empty($importer->source_plugin->sourceMapping)) {
$links[] = l(t('Edit source mapping'), 'admin/structure/crm-core/data-import/' . $key . '/source-mapping');
}
$links[] = l(t('Edit field mapping'), 'admin/structure/crm-core/data-import/' . $key . '/field-mapping');
$links[] = l(t('Edit settings'), 'admin/structure/crm-core/data-import/' . $key . '/settings');
$links[] = l(t('Delete'), 'admin/structure/crm-core/data-import/' . $key . '/delete');
$stats = _crm_core_data_import_migration_statistic_get($importer);
$items[$key] = array(
'title' => $importer->title,
'description' => $importer->description,
'lastimport' => empty($importer->lastimport) ? t('Unknown') : format_date($importer->lastimport, 'custom', 'Y-m-d H:i:s'),
'status' => _crm_core_data_import_migration_status($stats['status']),
'items' => $stats['total'],
'imported' => $stats['imported'],
'unprocessed' => $stats['total'] - $stats['processed'],
'operations' => theme(
'crm_core_ui_ctools_dropbutton',
array(
'ops_count' => count($links),
'links' => $links,
'index' => $key,
)
),
);
}
$form['operation'] = array(
'#type' => 'select',
'#title' => t('With selected:'),
'#options' => array(
'import' => t('Start import'),
'rollback' => t('Rollback'),
'deregister' => t('Remove migration settings'),
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Go'),
);
$form['items'] = array(
'#type' => 'tableselect',
'#header' => array(
'title' => t('Title'),
'description' => t('Description'),
'status' => t('Status'),
'items' => t('Items'),
'imported' => t('Imported'),
'unprocessed' => t('Unprocessed'),
'lastimport' => t('Last imported'),
'operations' => t('Operations'),
),
'#options' => $items,
'#empty' => t('No items available'),
);
$form['#attached']['css'][] = _crm_core_data_import_css_path();
return $form;
}
/**
* Submit handler for data import dashboard.
*/
function crm_core_data_import_dashboard_form_submit(&$form, &$form_state) {
$importers = $form_state['values']['items'];
$operation = $form_state['values']['operation'];
$operations = array();
$options = array('value' => 0, 'unit' => 'items');
foreach ($importers as $importer_id) {
if (!empty($importer_id)) {
$importer = crm_core_data_import_load_importer($importer_id);
switch ($operation) {
case 'import':
// If source not configured.
$source_fields = $importer->getSourceFields();
if (!empty($source_fields)) {
// Run import selected operation.
$mapping = $importer->getMappingSettings();
if (!empty($mapping)) {
_crm_core_data_import_build_entity_operations($operations, $mapping, $importer_id, $options);
}
else {
drupal_set_message(t('Mapping is empty. Please configure your !mapping.', array('!mapping' => l(t('mapping'), 'admin/structure/crm-core/data-import/' . $importer->id . '/field-mapping'))), 'error');
}
}
else {
drupal_set_message(t('Source fields are empty. Please configure your !source.', array('!source' => l(t('source'), 'admin/structure/crm-core/data-import/' . $importer->id . '/source-settings'))), 'error');
}
break;
case 'rollback':
// Rollback for all registered migrations.
$registered_migrations = variable_get('crm_core_data_import_migrations_' . $importer->id, array());
foreach ($registered_migrations as $machine_name) {
$migration = Migration::getInstance($machine_name);
if ($migration) {
$operations[] = array(
'crm_core_data_import_batch',
array('rollback', $machine_name, $options, 0),
);
}
}
break;
case 'deregister':
// Deregister all registered migrations.
$registered_migrations = variable_get('crm_core_data_import_migrations_' . $importer->id, array());
foreach ($registered_migrations as $machine_name) {
$migration = Migration::getInstance($machine_name);
if ($migration) {
Migration::deregisterMigration($machine_name);
drupal_set_message(t('Deregistered "@task_name" task', array('@task_name' => $machine_name)));
}
}
_crm_core_data_import_migration_statistic_reset($importer);
break;
}
if (count($operations) > 0) {
$batch = array(
'operations' => $operations,
'title' => t('Import processing'),
'file' => drupal_get_path('module', 'crm_core_data_import') . '/crm_core_data_import.admin.inc',
'init_message' => t('Starting import process'),
'progress_message' => '',
'error_message' => t('An error occurred. Some or all of the import processing has failed.'),
'finished' => 'crm_core_data_import_migration_batch_finish',
);
batch_set($batch);
// Set importer id for finished callback. Might be improved.
// There no another way to pass variable to finished callback.
$_SESSION['data_import_batch_importer_id'] = $importer_id;
}
}
}
}
/**
* Batch API item callback.
*/
function crm_core_data_import_batch($operation, $machine_name, $limit, $force, &$context) {
module_load_include('inc', 'migrate_ui', 'migrate_ui.pages');
migrate_ui_batch($operation, $machine_name, $limit, $force, $context);
}
/**
* Batch API finished callback. Trigger controllers for settings.
*/
function crm_core_data_import_migration_batch_finish($success, $results, $operations) {
if ($success) {
if (!empty($_SESSION['data_import_batch_importer_id'])) {
$importer = crm_core_data_import_load_importer($_SESSION['data_import_batch_importer_id']);
$importer->lastimport = time();
$importer->save();
_crm_core_data_import_migration_statistic_reset($importer);
crm_core_data_settings_batch($_SESSION['data_import_batch_importer_id']);
unset($_SESSION['data_import_batch_importer_id']);
}
}
}
/**
* Run batch for plugins.
*/
function crm_core_data_settings_batch($importer_id) {
// Get importer.
$operations = array();
$importer = crm_core_data_import_load_importer($importer_id);
$mapping = $importer->getMappingSettings();
if (!empty($mapping)) {
// Collect results.
foreach ($mapping as $key => $mapping_item) {
list($entity_controller_type, $entity_bundle, $bundle_delta) = explode(':', $key);
$entity_type = crm_core_data_import_get_destination_entity_type($entity_controller_type);
$machine_name = _crm_core_data_import_migration_machine_name($importer_id, $entity_type, $entity_bundle, $bundle_delta);
$migration = Migration::getInstance($machine_name);
if ($migration) {
$map = $migration->getMap();
$source_key_map = $map->getSourceKeyMap();
$importer_query = db_select($map->getMapTable(), 'map');
foreach ($source_key_map as $name => $alias) {
$importer_query->addField('map', $alias);
}
// There is no MigrateMap::getDestinationKeyMap() function. WTF?
$importer_query->addField('map', 'destid1');
foreach ($importer->getRelationDestinationEndPoints(implode(':', array($entity_type, $entity_bundle, $bundle_delta))) as $key => $ep) {
$importer_query->addField('map', 'relation_id' . ($key + 1));
}
$importer_result = $importer_query
->execute();
// Add to imported entities necessary information.
$entity_type = $migration->getEntityType();
$bundle = $migration->getEntityBundle();
foreach ($importer_result as $row) {
$data = array(
'entity_type' => $entity_type,
'bundle' => $bundle,
'entity_id' => $row->destid1,
'delta' => $bundle_delta,
);
foreach ($importer->getRelationDestinationEndPoints(implode(':', array($entity_type, $entity_bundle, $bundle_delta))) as $key => $endpoint) {
$name = 'relation_id' . ($key + 1);
$data[$name] = $row->{$name};
}
$source_keys = array();
foreach ($source_key_map as $name => $alias) {
$data[$alias] = $row->{$alias};
$source_keys[$alias] = $row->{$alias};
}
$operations[] = array(
'crm_core_data_run_settings_plugins_for_entity',
array($machine_name, $source_keys, $importer, $data),
);
}
}
}
if (count($operations) > 0) {
// Clear static $batch array to run new batch import.
$batch =& batch_get();
$batch = array();
$batch_definition = array(
'operations' => $operations,
'title' => t('Processing plugins settings'),
'file' => drupal_get_path('module', 'crm_core_data_import') . '/crm_core_data_import.admin.inc',
'init_message' => t('Starting process'),
'progress_message' => '',
'error_message' => t('An error occurred. Some or all of the import processing has failed.'),
'finished' => 'crm_core_data_run_settings_plugins_finish',
);
batch_set($batch_definition);
batch_process('admin/structure/crm-core/data-import');
}
}
}
/**
* Batch operation which trigger plugins for each imported entity.
*
* @param array $source_keys
*/
function crm_core_data_run_settings_plugins_for_entity($machine_name, $source_keys, $importer, $data, &$context) {
$importer_settings = $importer->getSettings();
if (!empty($importer_settings['settings_controllers'])) {
foreach ($importer_settings['settings_controllers'] as $controller) {
$settings_controller = crm_core_data_import_load_plugin_instance('crm_core_data_import_settings', $controller);
$settings_controller->postImport($importer, $data);
}
}
$context['results'][$machine_name] = t('Processed entities from @instance_name migrate instance.', array('@instance_name' => $machine_name));
// While in progress, show the cumulative list of messages.
$full_message = '';
foreach ($context['results'] as $message) {
$full_message .= $message . '<br />';
}
$context['message'] = $full_message;
}
/**
* Batch API finished callback for plugins.
*/
function crm_core_data_run_settings_plugins_finish($success, $results, $operations) {
drupal_set_message(t('Import successfully completed.'));
}
/**
* Page callback for source selection page.
*/
function crm_core_data_import_source_selection($form, &$form_state, $importer_id = FALSE) {
ctools_include('plugins');
$plugins = ctools_get_plugins('crm_core_data_import', 'crm_core_data_import_source');
$source_plugins = array();
foreach ($plugins as $id => $plugin) {
$source_plugins[$id] = $plugin['label'];
}
if ($importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
}
else {
$importer = new CRMCoreDataImport();
}
$form_state['importer'] = $importer;
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Data import name'),
'#required' => TRUE,
'#default_value' => $importer->title,
);
$form['machine_name'] = array(
'#type' => 'machine_name',
'#maxlength' => 32,
'#machine_name' => array(
'exists' => 'crm_core_data_importer_id_by_machine_name',
'source' => array('title'),
),
'#default_value' => empty($importer->machine_name) ? '' : $importer->machine_name,
'#disabled' => empty($importer->machine_name) ? FALSE : TRUE,
);
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#default_value' => $importer->description,
);
$form['source_plugin'] = array(
'#type' => 'radios',
'#title' => t('Where is your data coming from? Please select a source from the list below.'),
'#required' => TRUE,
'#options' => $source_plugins,
'#default_value' => $importer->source ? $importer->source : key($source_plugins),
);
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Next'),
);
$form['#attached']['css'][] = _crm_core_data_import_css_path();
crm_core_data_import_attach_pager($form, $importer, __FUNCTION__);
return $form;
}
/**
* Submit handler for source selection form.
*/
function crm_core_data_import_source_selection_submit(&$form, &$form_state) {
$values = $form_state['values'];
$importer = $form_state['importer'];
$importer->title = $values['title'];
$importer->machine_name = $values['machine_name'];
$importer->description = $values['description'];
$importer->source = $values['source_plugin'];
$importer->save();
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/source-settings';
}
/**
* Title callback for source settings page.
*/
function crm_core_data_import_source_settings_title_callback($importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
return $importer->title;
}
/**
* Page callback for source settings page.
*/
function crm_core_data_import_source_settings($form, &$form_state, $importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
$form_state['importer'] = $importer;
// Attach source config form.
$importer->source_plugin->configForm($form, $form_state, $importer->getSourceSettings());
$form['previous'] = array(
'#type' => 'submit',
'#value' => t('Previous'),
'#id' => 'button-previous',
);
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Next'),
'#id' => 'button-next',
);
$form['#attached']['css'][] = _crm_core_data_import_css_path();
crm_core_data_import_attach_pager($form, $importer, __FUNCTION__);
return $form;
}
/**
* Validation callback for source settings page.
*/
function crm_core_data_import_source_settings_validate(&$form, &$form_state) {
$importer = $form_state['importer'];
// Validate source settings.
$importer->source_plugin->configFormValidate($form, $form_state, $importer->getSourceSettings());
}
/**
* Submit callback for source settings page.
*/
function crm_core_data_import_source_settings_submit(&$form, &$form_state) {
$importer = $form_state['importer'];
// Submit source settings.
$settings = $importer->source_plugin->configFormSubmit($form, $form_state, $importer->getSourceSettings(), $importer->id);
// Set source settings.
$importer->setSourceSettings($settings);
$importer->save();
if ($form_state['triggering_element']['#id'] == 'button-previous') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/source-selection';
}
elseif ($form_state['triggering_element']['#id'] == 'button-next' && $importer->source_plugin->sourceMapping) {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/source-mapping';
}
elseif ($form_state['triggering_element']['#id'] == 'button-next') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/field-mapping';
}
}
/**
* Mapping for source.
*/
function crm_core_data_import_source_mapping($form, &$form_state, $importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
$form_state['importer'] = $importer;
if ($importer->source_plugin->sourceMapping) {
}
// Attach source config form.
$importer->source_plugin->sourceMappingForm($form, $form_state, $importer->getSourceSettings());
$form['previous'] = array(
'#type' => 'submit',
'#value' => t('Previous'),
'#id' => 'button-previous',
);
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Next'),
'#id' => 'button-next',
);
$form['#attached']['css'][] = _crm_core_data_import_css_path();
crm_core_data_import_attach_pager($form, $importer, __FUNCTION__);
return $form;
}
/**
* Validation callback for source mapping page.
*/
function crm_core_data_import_source_mapping_validate(&$form, &$form_state) {
$importer = $form_state['importer'];
// Validate source settings.
$importer->source_plugin->sourceMappingFormValidate($form, $form_state, $importer->getSourceSettings());
}
/**
* Submit callback for source settings page.
*/
function crm_core_data_import_source_mapping_submit(&$form, &$form_state) {
$importer = $form_state['importer'];
// Submit source settings.
$settings = $importer->source_plugin->sourceMappingFormSubmit($form, $form_state, $importer->getSourceSettings(), $importer->id);
// Set source settings.
$importer->setSourceSettings($settings);
$importer->save();
if ($form_state['triggering_element']['#id'] == 'button-previous') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/source-settings';
}
elseif ($form_state['triggering_element']['#id'] == 'button-next') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/field-mapping';
}
}
/**
* Title callback for field mapping page.
*/
function crm_core_data_import_field_mapping_title_callback($importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
return t('Field mapping for @title', array('@title' => $importer->title));
}
/**
* Page callback for field mapping page.
*/
function crm_core_data_import_field_mapping($form, &$form_state, $importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
$form_state['importer'] = $importer;
_crm_core_data_import_attach_linked_imports_form($form, $form_state);
// Build form_state from data import settings.
if (empty($form_state['values']['mapping']) && empty($form_state['triggering_element'])) {
$mapping_settings = $importer->getMappingSettings();
foreach ($mapping_settings as $key => $mapping_instance) {
list($entity_type, $entity_bundle,) = explode(':', $key);
$form_state['values']['mapping'][$key]['fields'] = $mapping_instance;
$entity_key = $entity_type . ':' . $entity_bundle;
if (empty($form_state['values']['mapping'][$entity_key . '_delta'])) {
$form_state['values']['mapping'][$entity_key . '_delta'] = 1;
}
else {
$form_state['values']['mapping'][$entity_key . '_delta']++;
}
}
}
$form['#tree'] = TRUE;
// Get available source fields.
$source_fields = $importer->getSourceFields();
_crm_core_data_import_attach_entity_form($form, $form_state);
$form['mapping'] = array(
'#type' => 'container',
'#prefix' => '<div id="mapping-fieldset-wrapper">',
'#suffix' => '</div>',
);
_crm_core_data_import_attach_fields_form($form, $form_state, $source_fields);
$form['previous'] = array(
'#type' => 'submit',
'#value' => t('Previous'),
'#id' => 'button-previous',
);
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Next'),
'#id' => 'button-next',
);
$form['#attached']['css'][] = _crm_core_data_import_css_path();
crm_core_data_import_attach_pager($form, $importer, __FUNCTION__);
return $form;
}
/**
* Submit callback for field mapping page.
*/
function crm_core_data_import_field_mapping_submit(&$form, &$form_state) {
/** @var CRMCoreDataImport $importer */
$importer = $form_state['importer'];
$mapping = array();
// Save linked imports, if any.
$importer->setLinkedImports($form_state['linked_imports']);
// Build data import settings from form_state.
if (!empty($form_state['values']['mapping'])) {
$mapping_values = $form_state['values']['mapping'];
foreach ($mapping_values as $key => $mapping_instance) {
if (is_array($mapping_instance)) {
foreach ($mapping_instance['fields'] as $field_key => $field_value) {
if (!empty($field_value['remove_field'])) {
unset($mapping_instance['fields'][$field_key]['remove_field']);
}
}
$mapping[$key] = $mapping_instance['fields'];
}
}
$importer->setMappingSettings($mapping);
}
else {
$importer->setMappingSettings(array());
}
// Remove unnecessary entities from settings before save.
$settings = $importer->getSettings();
foreach ($settings as $settings_key => $item) {
if (!empty($item['fields'])) {
foreach ($item['fields'] as $settings_field_key => $settings_field) {
$source_conrtoller_key = _crm_core_data_import_controller_key_by_entity_key($settings_field['source']);
$destination_conrtoller_key = _crm_core_data_import_controller_key_by_entity_key($settings_field['destination']);
if (!array_key_exists($source_conrtoller_key, $mapping) || !array_key_exists($destination_conrtoller_key, $mapping)) {
unset($settings[$settings_key]['fields'][$settings_field_key]);
}
}
}
}
$importer->setSettings($settings);
$importer->save();
if ($form_state['triggering_element']['#id'] == 'button-previous' && $importer->source_plugin->sourceMapping) {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/source-mapping';
}
elseif ($form_state['triggering_element']['#id'] == 'button-previous') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/source-settings';
}
elseif ($form_state['triggering_element']['#id'] == 'button-next') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/settings';
}
}
/**
* Entity types and bundles.
*/
function _crm_core_data_import_attach_entity_form(&$form, &$form_state) {
ctools_include('plugins');
$plugins = ctools_get_plugins('crm_core_data_import', 'crm_core_data_import_destination');
$entity_plugins = array();
$entity_bundles = array();
foreach ($plugins as $id => $plugin) {
$entity_plugins[$id] = $plugin['label'];
}
$form['entity_form'] = array(
'#type' => 'container',
'#prefix' => '<div id="entity-form-fieldset-wrapper">',
'#suffix' => '</div>',
);
$form['entity_form']['entity_type'] = array(
'#type' => 'select',
'#title' => t('Add an:'),
'#empty_option' => t('- Entity type -'),
'#options' => $entity_plugins,
'#ajax' => array(
'callback' => '_crm_core_data_import_entity_form_entity_type_callback',
'wrapper' => 'entity-form-fieldset-wrapper',
),
);
if (!empty($form_state['values']['entity_form']['entity_type'])) {
$destination = crm_core_data_import_load_plugin_instance('crm_core_data_import_destination', $form_state['values']['entity_form']['entity_type']);
$entity_bundles = $destination->getBundles();
}
$form['entity_form']['entity_bundle'] = array(
'#type' => 'select',
'#title' => t('of type:'),
'#options' => $entity_bundles,
);
$form['entity_form']['add_entity'] = array(
'#type' => 'button',
'#id' => 'add-entity-button',
'#value' => t('Add'),
'#ajax' => array(
'callback' => '_crm_core_data_import_entity_form_add_entity_callback',
'method' => 'replace',
'wrapper' => 'mapping-fieldset-wrapper',
),
);
}
/**
* Entity fields and bundles.
*/
function _crm_core_data_import_attach_fields_form(&$form, &$form_state, $source_fields) {
$importer = $form_state['importer'];
// Button which was triggered.
$triggering_element = !empty($form_state['triggering_element']) ? $form_state['triggering_element'] : FALSE;
// If button is remove bundle.
if (!empty($triggering_element['#parents'][2]) && $triggering_element['#parents'][2] == 'remove_bundle') {
$key = $triggering_element['#parents'][1];
if (!empty($form_state['values']['mapping'][$key])) {
unset($form_state['values']['mapping'][$key]);
}
}
// If buttons are move up or move down.
if (!empty($triggering_element['#parents'][2]) && ($triggering_element['#parents'][2] == 'move_down' || $triggering_element['#parents'][2] == 'move_up')) {
$key = $triggering_element['#parents'][1];
$search = FALSE;
$swap_mapping = $form_state['values']['mapping'];
// If move up, reverse array.
if ($triggering_element['#parents'][2] == 'move_down') {
$mapping = $form_state['values']['mapping'];
}
else {
$mapping = array_reverse($form_state['values']['mapping']);
}
foreach ($mapping as $mapping_key => $mapping_item) {
if ($mapping_key == $key) {
$search = TRUE;
}
elseif ($search == TRUE && is_array($mapping_item)) {
$search = FALSE;
$swap_mapping = _crm_core_data_import_array_swap($swap_mapping, $key, $mapping_key);
}
}
$form_state['values']['mapping'] = $swap_mapping;
}
// If button is remove field.
if (!empty($triggering_element['#parents'][4]) && $triggering_element['#parents'][4] == 'remove_field') {
$entity_bundle_key = $triggering_element['#parents'][1];
$field_key = $triggering_element['#parents'][3];
unset($form_state['values']['mapping'][$entity_bundle_key]['fields'][$field_key]);
}
// Build form from form_state.
if (!empty($form_state['values']['mapping'])) {
// Attach elements entity fields.
foreach ($form_state['values']['mapping'] as $key => $mapping) {
if (is_array($mapping)) {
list($entity_type, $entity_bundle, $bundle_delta) = explode(':', $key);
$destination = crm_core_data_import_load_plugin_instance('crm_core_data_import_destination', $entity_type);
$fields = $destination->getFields($entity_bundle);
$html_id = drupal_html_id($key);
// Add field with count of entities.
$entity_key = $entity_type . ':' . $entity_bundle;
$form['mapping'][$entity_key . '_delta'] = array(
'#type' => 'value',
'#value' => $form_state['values']['mapping'][$entity_key . '_delta'],
);
// If was triggered add-more-button, add new field.
if (strpos($triggering_element['#id'], 'add-more') !== FALSE && $triggering_element['#parents'][1] == $key) {
$form_state['values']['mapping'][$key]['fields'][] = array('source_field' => '', 'destination_field' => '');
}
foreach ($form_state['values']['mapping'][$key]['fields'] as $delta => $field) {
$source_fields_values = $source_fields;
$importer->source_plugin->mappingSourceFieldsAlter($source_fields_values, crm_core_data_import_get_destination_entity_type($entity_type), $entity_bundle, $importer);
if ($delta === 'primary') {
// Attach primary field.
_crm_core_data_import_attach_elements_primary_fieldset($form, $form_state, $entity_type, $entity_bundle, $key, $html_id, $source_fields_values, $bundle_delta);
}
else {
// Attach form elements for fields.
_crm_core_data_import_attach_elements_field($form, $form_state, $key, $delta, $source_fields_values, $fields);
}
}
// Attach add more button.
_crm_core_data_import_attach_elements_add_more_button($form, $form_state, $key, $html_id);
}
}
}
// Add fieldset form new entity.
if (!empty($form_state['values']['entity_form']['entity_type']) && !empty($form_state['values']['entity_form']['entity_bundle']) && $triggering_element['#id'] == 'add-entity-button') {
$entity_type = $form_state['values']['entity_form']['entity_type'];
$entity_bundle = $form_state['values']['entity_form']['entity_bundle'];
$key = $entity_type . ':' . $entity_bundle;
// Save count of entity bundle. Need to support multiple bundles.
if (empty($form_state['values']['mapping'][$key . '_delta'])) {
// If initial adding.
$form_state['values']['mapping'][$key . '_delta'] = 1;
$bundle_delta = 1;
}
else {
// If bundle already exist.
$form_state['values']['mapping'][$key . '_delta']++;
$bundle_delta = $form_state['values']['mapping'][$key . '_delta'];
}
$form['mapping'][$key . '_delta'] = array(
'#type' => 'value',
'#value' => $bundle_delta,
);
$key .= ':' . $bundle_delta;
$html_id = drupal_html_id($key);
$source_fields_values = $source_fields;
$importer->source_plugin->mappingSourceFieldsAlter($source_fields_values, crm_core_data_import_get_destination_entity_type($entity_type), $entity_bundle, $importer);
_crm_core_data_import_attach_elements_primary_fieldset($form, $form_state, $entity_type, $entity_bundle, $key, $html_id, $source_fields_values, $bundle_delta);
_crm_core_data_import_attach_elements_add_more_button($form, $form_state, $key, $html_id);
}
$importer->source_plugin->fieldMappingFormAlter($form, $form_state);
}
/**
* Attach primary fieldset for entity bundle.
*
* @param array $form
* Main form.
* @param array $form_state
* Main form state.
* @param string $entity_type
* Entity type.
* @param string $entity_bundle
* Entity bundle.
* @param string $key
* Key of fieldset.
* @param string $html_id
* HTML id for fieldset wrapper.
* @param array $source_fields
* List of available fields from source.
* @param string $bundle_delta
* Delta of bundle.
*/
function _crm_core_data_import_attach_elements_primary_fieldset(&$form, &$form_state, $entity_type, $entity_bundle, $key, $html_id, $source_fields, $bundle_delta) {
if (empty($source_fields)) {
$source_key = !empty($form_state['values']['mapping'][$key]['fields']['primary']['source_field_primary']) ? $form_state['values']['mapping'][$key]['fields']['primary']['source_field_primary'] : 0;
$source_fields = array($source_key => t('Unavailable'));
}
$form['mapping'][$key] = array(
'#type' => 'container',
'#prefix' => '<div id="' . $html_id . '-wrapper">',
'#suffix' => '</div>',
'#attributes' => array(
'class' => array('entity-fieldset-wrapper'),
),
);
$form['mapping'][$key]['text'] = array(
'#markup' => '<h3>' . crm_core_data_import_get_destination_label($entity_type, $entity_bundle, $bundle_delta) . '</h3>',
);
$form['mapping'][$key]['move_up'] = array(
'#type' => 'button',
'#value' => t('Move Up'),
'#name' => $html_id . '-move-up-button',
'#ajax' => array(
'callback' => '_crm_core_data_import_entity_type_action_callback',
'method' => 'replace',
'wrapper' => 'mapping-fieldset-wrapper',
),
);
$form['mapping'][$key]['move_down'] = array(
'#type' => 'button',
'#value' => t('Move Down'),
'#name' => $html_id . '-move-down-button',
'#ajax' => array(
'callback' => '_crm_core_data_import_entity_type_action_callback',
'method' => 'replace',
'wrapper' => 'mapping-fieldset-wrapper',
),
);
$form['mapping'][$key]['remove_bundle'] = array(
'#type' => 'button',
'#value' => t('Remove'),
'#name' => $html_id . '-remove-button',
'#ajax' => array(
'callback' => '_crm_core_data_import_entity_type_action_callback',
'method' => 'replace',
'wrapper' => 'mapping-fieldset-wrapper',
),
);
$form['mapping'][$key]['fields'] = array(
'#type' => 'container',
);
$form['mapping'][$key]['fields']['primary'] = array(
'#type' => 'container',
'#attributes' => array(
'class' => array('field-fieldset-wrapper'),
),
);
$form['mapping'][$key]['fields']['primary']['source_field_primary'] = array(
'#type' => 'select',
'#options' => $source_fields,
'#default_value' => !empty($form_state['values']['mapping'][$key]['fields']['primary']['source_field_primary']) ? $form_state['values']['mapping'][$key]['fields']['primary']['source_field_primary'] : FALSE,
);
$form['mapping'][$key]['fields']['primary']['destination_field_primary'] = array(
'#type' => 'select',
'#options' => array('primary_field' => t('Primary field')),
'#default_value' => 'primary_field',
'#disabled' => TRUE,
);
}
/**
* Attach add more button to entity bundle fieldset.
*
* @param array $form
* Main form.
* @param array $form_state
* Main form state.
* @param string $key
* Key of fieldset.
* @param string $html_id
* HTML id for fieldset wrapper.
*/
function _crm_core_data_import_attach_elements_add_more_button(&$form, &$form_state, $key, $html_id) {
$form['mapping'][$key]['add_more'] = array(
'#type' => 'button',
'#default_value' => t('Add Another Field'),
'#name' => $html_id . '-button',
'#ajax' => array(
'callback' => '_crm_core_data_import_add_another_field_callback',
'method' => 'replace',
'wrapper' => $html_id . '-wrapper',
),
);
}
/**
* Attach mapping field to entity bundle fieldset.
*
* @param array $form
* Main form.
* @param array $form_state
* Main form state.
* @param string $key
* Key of fieldset.
* @param int $delta
* Delta in the current fieldset.
* @param array $source_fields
* List of available fields from source.
* @param array $fields
* List of available fields from destination.
*/
function _crm_core_data_import_attach_elements_field(&$form, &$form_state, $key, $delta, $source_fields, $fields) {
if (empty($source_fields)) {
$source_key = !empty($form_state['values']['mapping'][$key]['fields'][$delta]['source_field']) ? $form_state['values']['mapping'][$key]['fields'][$delta]['source_field'] : 0;
$source_fields = array($source_key => t('Unavailable'));
}
else {
$source_fields = array('default_value' => t('(provide value)')) + $source_fields;
}
$form['mapping'][$key]['fields'][$delta] = array(
'#type' => 'container',
'#attributes' => array(
'class' => array('field-fieldset-wrapper'),
),
);
$form['mapping'][$key]['fields'][$delta]['source_field'] = array(
'#type' => 'select',
'#options' => $source_fields,
'#default_value' => !empty($form_state['values']['mapping'][$key]['fields'][$delta]['source_field']) ? $form_state['values']['mapping'][$key]['fields'][$delta]['source_field'] : FALSE,
);
$form['mapping'][$key]['fields'][$delta]['destination_field'] = array(
'#type' => 'select',
'#options' => $fields,
'#default_value' => !empty($form_state['values']['mapping'][$key]['fields'][$delta]['destination_field']) ? $form_state['values']['mapping'][$key]['fields'][$delta]['destination_field'] : FALSE,
);
$form['mapping'][$key]['fields'][$delta]['default_value'] = array(
'#type' => 'textfield',
'#default_value' => !empty($form_state['values']['mapping'][$key]['fields'][$delta]['default_value']) ? $form_state['values']['mapping'][$key]['fields'][$delta]['default_value'] : FALSE,
);
$form['mapping'][$key]['fields'][$delta]['remove_field'] = array(
'#type' => 'button',
'#default_value' => t('Remove'),
'#name' => 'remove-field-button-' . drupal_html_id($key . $delta),
'#ajax' => array(
'callback' => '_crm_core_data_import_entity_type_action_callback',
'method' => 'replace',
'wrapper' => 'mapping-fieldset-wrapper',
),
);
}
/**
* Callback for entity type select.
*/
function _crm_core_data_import_entity_form_entity_type_callback($form, &$form_state) {
return $form['entity_form'];
}
/**
* Callback for entity fieldset submit.
*/
function _crm_core_data_import_entity_form_add_entity_callback($form, &$form_state) {
_crm_core_data_import_theme_mapping_form($form);
return $form['mapping'];
}
/**
* Callback for add another field button.
*/
function _crm_core_data_import_add_another_field_callback($form, &$form_state) {
_crm_core_data_import_theme_mapping_form($form);
$elemets = $form_state['triggering_element']['#parents'][1];
return $form['mapping'][$elemets];
}
/**
* Callback for actions for entity bundle.
*/
function _crm_core_data_import_entity_type_action_callback($form, &$form_state) {
_crm_core_data_import_theme_mapping_form($form);
return $form['mapping'];
}
/**
* Page callback for settings page.
*/
function crm_core_data_import_settings_page($form, &$form_state, $importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
$form_state['importer'] = $importer;
$form['#tree'] = TRUE;
$form['form_header'] = array(
'#markup' => '<p>' . t('Use the settings on this screen to refine the data being imported into the system.') . '</p>',
'#weight' => -50,
);
$plugins = ctools_get_plugins('crm_core_data_import', 'crm_core_data_import_settings');
foreach ($plugins as $plugin) {
$data_import_settings = crm_core_data_import_load_plugin_instance('crm_core_data_import_settings', $plugin['name']);
if ($data_import_settings->displayConditions($importer)) {
$data_import_settings->configForm($form, $form_state, $importer, $plugin['label']);
}
}
$form['previous'] = array(
'#type' => 'submit',
'#value' => t('Previous'),
'#id' => 'button-previous',
);
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#id' => 'button-next',
);
$form['#attached']['css'][] = _crm_core_data_import_css_path();
crm_core_data_import_attach_pager($form, $importer, __FUNCTION__);
return $form;
}
/**
* Validation callback for settings page.
*/
function crm_core_data_import_settings_page_validate(&$form, &$form_state) {
$importer = $form_state['importer'];
ctools_include('plugins');
$plugins = ctools_get_plugins('crm_core_data_import', 'crm_core_data_import_settings');
foreach ($plugins as $plugin) {
$data_import_settings = crm_core_data_import_load_plugin_instance('crm_core_data_import_settings', $plugin['name']);
$data_import_settings->configFormValidate($form, $form_state, $importer);
}
}
/**
* Submit callback for settings page.
*/
function crm_core_data_import_settings_page_submit(&$form, &$form_state) {
$importer = $form_state['importer'];
ctools_include('plugins');
$plugins = ctools_get_plugins('crm_core_data_import', 'crm_core_data_import_settings');
foreach ($plugins as $plugin) {
$data_import_settings = crm_core_data_import_load_plugin_instance('crm_core_data_import_settings', $plugin['name']);
if ($data_import_settings->displayConditions($importer)) {
$settings = $data_import_settings->configFormSubmit($form, $form_state, $importer);
$current_settings = $importer->getSettings();
if (!empty($settings)) {
$result_settings = array_merge($current_settings, $settings);
}
else {
$result_settings = $current_settings;
}
$controller = get_class($data_import_settings);
if (empty($result_settings['settings_controllers']) || !in_array($controller, $result_settings['settings_controllers'])) {
$result_settings['settings_controllers'][] = $controller;
}
$importer->setSettings($result_settings);
}
}
$importer->save();
if ($form_state['triggering_element']['#id'] == 'button-previous') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import/' . $importer->id . '/field-mapping';
}
elseif ($form_state['triggering_element']['#id'] == 'button-next') {
$form_state['redirect'] = 'admin/structure/crm-core/data-import';
}
}
/**
* Page to delete data import task.
*/
function crm_core_data_import_delete_page($form, &$form_state, $importer_id) {
$importer = crm_core_data_import_load_importer($importer_id);
$form_state['importer'] = $importer;
return confirm_form($form,
t('Are you sure you want to delete data import task %title?', array('%title' => $importer->title)),
'admin/structure/crm-core/data-import',
t('This action cannot be undone.'),
t('Delete'),
t('Cancel')
);
}
/**
* Submit callback to delete data import task.
*/
function crm_core_data_import_delete_page_submit($form, &$form_state) {
$importer = $form_state['importer'];
// Remove all registered migrations.
$registered_migrations = variable_get('crm_core_data_import_migrations_' . $importer->id, array());
foreach ($registered_migrations as $machine_name) {
$migration = Migration::getInstance($machine_name);
if ($migration) {
Migration::deregisterMigration($machine_name);
}
}
variable_del('crm_core_data_import_migrations_' . $importer->id);
db_delete('crm_core_data_import')
->condition('id', $importer->id)
->execute();
$form_state['redirect'] = 'admin/structure/crm-core/data-import';
}
/**
* Build operations for queue of import.
*/
function _crm_core_data_import_build_entity_operations(&$operations, $mapping, $importer_id, $options) {
foreach ($mapping as $key => $mapping_item) {
list($entity_controller_type, $entity_bundle, $bundle_delta) = explode(':', $key);
$entity_type = crm_core_data_import_get_destination_entity_type($entity_controller_type);
crm_core_data_import_register_migration($importer_id, $entity_type, $entity_bundle, $bundle_delta);
$machine_name = _crm_core_data_import_migration_machine_name($importer_id, $entity_type, $entity_bundle, $bundle_delta);
$operations[] = array(
'crm_core_data_import_batch',
array('import', $machine_name, $options, 0),
);
}
}
/** Past this line added for linked data imports */
/**
* Attach linked import subform.
*/
function _crm_core_data_import_attach_linked_imports_form(&$form, &$form_state) {
/** @var CRMCoreDataImport $importer */
$importer = $form_state['importer'];
// Build dependent data imports.
// Data import cannot depend on itself, make the list of other data imports.
if (!isset($form_state['linked_imports'])) {
$form_state['linked_imports'] = $importer->getLinkedImports();
}
$extracted_condition = db_and()->condition('id', $importer->id, '<>');
$candidates = CRMCoreDataImport::getIds(array($extracted_condition));
if ($candidates || !empty($form_state['linked_imports'])) {
$options = array();
if (!isset($form_state['linked_imports'])) {
$form_state['linked_imports'] = array();
}
// Exclude already selected imports
foreach ($candidates as $candidate_id) {
if (array_key_exists($candidate_id, $form_state['linked_imports'])) {
continue;
}
$object = crm_core_data_import_load_importer($candidate_id);
$options[$candidate_id] = $object->title;
}
$form['linked_wrapper'] = array(
'#type' => 'fieldset',
'#title' => t('Linked imports'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#attributes' => array('class' => array('ccdi-linked')),
);
if ($options) {
$form['linked_wrapper']['data_import'] = array(
'#type' => 'select',
'#title' => t('Available data imports'),
'#options' => $options,
);
$form['linked_wrapper']['primary_field'] = array(
'#type' => 'select',
'#title' => t('Source field'),
'#description' => t('Primary source field to identify imported elements'),
'#options' => $importer->getSourceFields(),
);
$form['linked_wrapper']['add'] = array(
'#type' => 'submit',
'#value' => t('Link'),
'#submit' => array('_crm_core_data_import_linked_add'),
'#ajax' => array(
'callback' => '_crm_core_data_import_ajax_linked_content',
),
);
}
if ($form_state['linked_imports']) {
$header = array(
t('Linked imports'),
t('Source'),
t('Actions'),
);
foreach ($form_state['linked_imports'] as $linked_id => $name) {
$object = crm_core_data_import_load_importer($linked_id);
$button = array(
'#type' => 'submit',
'#value' => t('Remove'),
'#submit' => array(
'_crm_core_data_import_linked_remove',
),
'#ajax' => array(
'callback' => '_crm_core_data_import_ajax_linked_content',
),
);
$rows[] = array($object->title, $name, render($button));
$form['linked_imports']['button_remove_' . $linked_id] = $button;
}
$form['linked_wrapper']['existing'] = array(
'#type' => 'markup',
'#markup' => theme('table', array(
'header' => $header,
'rows' => $rows,
)),
);
}
}
}
function _crm_core_data_import_ajax_linked_content(&$form, &$form_state) {
$markup = render($form['linked_wrapper']);
return array(
'#type' => 'ajax',
'#commands' => array(ajax_command_replace('.ccdi-linked', $markup)),
);
}
function _crm_core_data_import_linked_add(&$form, &$form_state) {
$form_state['rebuild'] = TRUE;
$form_state['linked_imports'][$form_state['values']['linked_wrapper']['data_import']] = $form_state['values']['linked_wrapper']['primary_field'];
}
function _crm_core_data_import_linked_remove(&$form, &$form_state) {
$form_state['rebuild'] = TRUE;
$form_state['linked_imports'] = array();
}
|
/*🚀 1. Use o método forEach para exibir a lista de emails com a seguinte frase: O email ${email} está cadastrado em nosso banco de dados!. */
const emailListInData = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
];
emailListInData.forEach(email => console.log(`O email ${email} está cadastrado em nosso banco de dados!`));
/*🚀 2. Utilize o método find para retornar o primeiro número do array que é divisível por 3 e 5, caso ele exista. */
const numbers = [19, 21, 30, 3, 45, 22, 15];
const verifyNumbers = numbers.find((number) => number % 3 === 0 && number % 5 === 0);
console.log(`O primeiro número encontrado do array que é divisível por 3 e 5 é ${verifyNumbers}.`);
// ---------------------------------------------
/*🚀 3. Utilize o find para encontrar o primeiro nome com cinco letras, caso ele exista. */
const names = ['João', 'Irene', 'Fernando', 'Maria'];
const countLetters = names.find((name) => name.length === 5);
console.log(`O primeiro nome encontrado com cinco letras é ${countLetters}.`);
// ---------------------------------------------
/*🚀 4. Utilize o find para encontrar a música com id igual a '31031685', caso ela exista. */
const songs = [
{ id: '31031685', title: 'Partita in C moll BWV 997' },
{ id: '31031686', title: 'Toccata and Fugue, BWV 565' },
{ id: '31031687', title: 'Chaconne, Partita No. 2 BWV 1004' },
];
const findSong = songs.find((song) => song.id === '31031685');
// console.log(`A música com id igual a '31031685' encontrada é ${findSong}.`);
console.log(findSong);
/* 🚀 5. Você ficou responsável por conferir a lista de pessoas convidadas de uma festa de casamento e precisa verificar se o nome da pessoa está ou não na lista. Para isso, você deve utilizar o código abaixo e desenvolver sua lógica a partir dele:
O nome das pessoas convidadas está salvo em um array chamado guests.
A função hasName é responsável por verificar se o nome da pessoa está ou não na lista. Essa função recebe dois parâmetros: arr, que é o array com o nome das pessoas convidadas, e name, que é o nome a ser verificado na lista de convidados (array guests).
Caso a pessoa esteja na lista de convidados, o retorno da função hasName deve ser true. Caso contrário, deve ser false. */
const guests = ['Mateus', 'José', 'Ana', 'Cláudia', 'Bruna'];
const hasName = (arr, name) => {
return arr.some((guest) => guest === name);
};
console.log(hasName(guests, 'Ana'));
console.log(hasName(guests, 'Pedro'));
/* Você ficou responsável por criar um sistema que verifica se as pessoas da mesma turma possuem uma determinada faixa de idade. Você deve utilizar o array people e desenvolver a sua lógica a partir dele. Para isso: crie uma função que verifica se todas as pessoas do array people possuem a idade mínima especificada.
Retorne true se todas tiverem a idade maior ou igual à mínima e, caso contrário, false. */
const people = [
{ name: 'Mateus', age: 18 },
{ name: 'José', age: 16 },
{ name: 'Ana', age: 23 },
{ name: 'Cláudia', age: 20 },
{ name: 'Bruna', age: 19 },
];
const verifyAges = (array, minimumAge) => {
return array.every((person) => person.age >= minimumAge);
}
console.log(verifyAges(people, 18)); // false
console.log(verifyAges(people, 10)); // true
|
import org.apache.lucene.analysis.*;
import java.io.IOException;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
/**
* Abstract base class for TokenFilters that may remove tokens.
* You have to implement {@link #accept} and return a boolean if the current
* token should be preserved. {@link #incrementToken} uses this method
* to decide if a token should be passed to the caller.
*/
public abstract class FilteringTokenFilter extends TokenFilter {
private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
private int skippedPositions;
/**
* Create a new {@link FilteringTokenFilter}.
* @param in the {@link TokenStream} to consume
*/
public FilteringTokenFilter(TokenStream in) {
super(in);
}
/** Override this method and return if the current input token should be returned by {@link #incrementToken}. */
protected abstract boolean accept() throws IOException;
@Override
public final boolean incrementToken() throws IOException {
skippedPositions = 0;
while (input.incrementToken()) {
if (accept()) {
if (skippedPositions != 0) {
posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement() + skippedPositions);
}
return true;
}
skippedPositions += posIncrAtt.getPositionIncrement();
}
// reached EOS -- return false
return false;
}
@Override
public void reset() throws IOException {
super.reset();
skippedPositions = 0;
}
@Override
public void end() throws IOException {
super.end();
posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement() + skippedPositions);
}
}
|
OPTLIB is an optimization library. The standard usage is to
minimize a function that returns a double variable based
on some array of inputs that are also stored as doubles.
OPTLIB currently supports minimization by Powell's method,
Monte Carlo trials of Powell's method, a Genetic Algorithm,
and ensemble-based Simulated Annealing.
OPTLIB requires the user to specify a function of the form
double func(double * x, void * func_data). func_data is
a user specified structure which can be NULL that is passed
directly to func, allowing the user to pass parameters to func
without specifying them as global variables.
A typical use of optlib is as follows:
double func(double *x, void * func_data) {
int * fcount = (int *)func_data;
fcount++;
return x[0]*x[0]+x[1]*x[1]; // x^2+y^2;
}
int main(int argc, char ** argv) {
OptLibOpts * theOpts;
int fcount=0;
seed_by_time(0);
theOpts = OPTLIB_CreateOpts(); //set up default options
theOpts->ga_npools=1; // override defaults (see optlib.c optlib.h)
theOpts->method = OPTLIB_METHOD_GA; //set method, default is GA
guess[0]=...; //initialize guess
guess[1]=...;
OPTLIB_Minimize(theOpts,n,guess,NULL,&func,(void *)&fcount); // minimize
printf("SOLUTION %g %g\n",guess[0], guess[1]);
printf("TOTAL FUNCTION CALLS %d\n",fcount);
OPTLIB_DestroyOpts(theOpts); //free memory
}
MPI OPTLIB
Driver routines exist in the source directory showing the use of
OptLib with MPI options turned on.
To compile libopt_mpi.a, set USE_MPI to ON in cmake. This will create
libopt_mpi.a instead of libopt.a. When implementing, include <libopt_mpi.h>
instead of <libopt.h> (which will define the preprocessor variable USE_OPTMPI),
and link using the -lopt_mpi flag instead of the -lopt flag.
|
/// @file utilities.h
/// @brief SoundTailor common maths header
/// @author gm
/// @copyright gm 2016
///
/// This file is part of SoundTailor
///
/// SoundTailor is free software: you can redistribute it and/or modify
/// it under the terms of the GNU General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// SoundTailor 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 SoundTailor. If not, see <http://www.gnu.org/licenses/>.
#ifndef SOUNDTAILOR_SRC_UTILITIES_H_
#define SOUNDTAILOR_SRC_UTILITIES_H_
#include "soundtailor/src/maths.h"
namespace soundtailor {
/// @brief Block process function (generators-like)
///
/// In a context of dynamic polymorphism this will save you from per-sample
/// virtual function calls
/// The compiler should be able to inline it
/// obviously the instance has to be known at compile time
template <typename GeneratorType>
void ProcessBlock(BlockOut out,
std::size_t block_size,
GeneratorType&& instance) {
float* SOUNDTAILOR_RESTRICT out_write(out);
for (std::size_t i(0); i < block_size; i += SampleSize) {
VectorMath::Store(out_write, instance());
out_write += SampleSize;
}
}
/// @brief Block process function (filters-like)
///
/// In a context of dynamic polymorphism this will save you from per-sample
/// virtual function calls
/// The compiler should be able to inline it
/// obviously the instance has to be known at compile time
template <typename FilterType>
void ProcessBlock(BlockIn in,
BlockOut out,
std::size_t block_size,
FilterType&& filter_instance) {
const float* SOUNDTAILOR_RESTRICT in_ptr(in);
float* SOUNDTAILOR_RESTRICT out_write(out);
for (std::size_t i(0); i < block_size; i += SampleSize) {
const Sample kInput(VectorMath::Fill(in_ptr));
VectorMath::Store(out_write, filter_instance(kInput));
in_ptr += SampleSize;
out_write += SampleSize;
}
}
} // namespace soundtailor
#endif // SOUNDTAILOR_SRC_UTILITIES_H_
|
package com.f1elle.prng.prng.ui.utils
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.f1elle.prng.theme.Border
@Composable
fun textField(title: String,
textFieldValue: String,
onValueChange: (String) -> Unit,
keyboardOptions: KeyboardOptions){
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(end = 100.dp, start = 50.dp)){
Text(title, style = TextStyle(color = Color.White, fontSize = 16.sp))
Spacer(Modifier.weight(1f))
BasicTextField(value = textFieldValue,
modifier = Modifier.border(width = 1.5.dp,
shape = RoundedCornerShape(7.dp),
brush = SolidColor(Border)).padding(5.dp),
onValueChange = onValueChange,
keyboardOptions = keyboardOptions,
enabled = true,
singleLine = true,
textStyle = TextStyle(
color = Color.White,
fontSize = 16.sp),
cursorBrush = SolidColor(Color.White),
decorationBox = {
innerTextField ->
Row{
Text(text=textFieldValue, color = Color.Transparent)
}
innerTextField()
}
)
}
}
|
# Artificial Intelligence Nanodegree
## Introductory Project: Diagonal Sudoku Solver
# Question 1 (Naked Twins)
Q: How do we use constraint propagation to solve the naked twins problem?
A: *Student should provide answer here*
In brief, for the naked twins problem, the constraint/condition is that the shared peers of the twins must not contain any of the 2 digits of the twins.
This condition is propagated to all twins in the board.
# Question 2 (Diagonal Sudoku)
Q: How do we use constraint propagation to solve the diagonal sudoku problem?
A: *Student should provide answer here*
With the diagonal sudoku, we only need to add 2 additional "items" to the standard set of units: row, column, square (3x3), and now diagonal down (from A1 to I9) and diagonal up (from A9 to I1). Then, we apply the same constraints that we use for the standard sudoku. For example, in the case of the naked twins, the shared peers of the twins might include boxes on the diagonal.
### Install
This project requires **Python 3**.
We recommend students install [Anaconda](https://www.continuum.io/downloads), a pre-packaged Python distribution that contains all of the necessary libraries and software for this project.
Please try using the environment we provided in the Anaconda lesson of the Nanodegree.
##### Optional: Pygame
Optionally, you can also install pygame if you want to see your visualization. If you've followed our instructions for setting up our conda environment, you should be all set.
If not, please see how to download pygame [here](http://www.pygame.org/download.shtml).
### Code
* `solutions.py` - You'll fill this in as part of your solution.
* `solution_test.py` - Do not modify this. You can test your solution by running `python solution_test.py`.
* `PySudoku.py` - Do not modify this. This is code for visualizing your solution.
* `visualize.py` - Do not modify this. This is code for visualizing your solution.
### Visualizing
To visualize your solution, please only assign values to the values_dict using the ```assign_values``` function provided in solution.py
### Data
The data consists of a text file of diagonal sudokus for you to solve.
|
\exercice{2009, ridde, 1999/11/01}
\enonce
Soient $A, B, C, D$ quatre points distincts du plan tels que $\overrightarrow{AB}
\neq \overrightarrow{CD}$. Montrer que le centre de la similitude directe transformant $A$ en $C$
et $B$ en $D$ est aussi le centre de celle transformant $A$ en $B$ et $C$ en $D$.
\finenonce
\indication
Utiliser par exemple les nombres complexes.
\finindication
\correction
Soit $z\mapsto \alpha z + \beta$ la représentation en coordonnée complexe de la similitude directe envoyant $A$ sur $C$ et $B$ sur $D$. On a donc
\[
\left\{\begin{array}{lc}\alpha a+\beta &= c \\ \alpha b+\beta &= d\\ \end{array}\right.
\] ce qui donne $\alpha = \frac{c-d}{a-b}$ et $\beta=\frac{ad-bc}{a-b}$. D'après la condition fixée par l'énoncé, on a $\alpha\neq 1$ donc cette similitude admet un unique point fixe $\Omega$ d'affixe
\[
\omega = \frac{\beta}{1-\alpha} = \frac{ad-bc}{a-b-c+d}.
\]
On remarque que l'expression de $\omega$ est inchangée en permutant $b$ et $c$. Cela signifie qu'en faisant les mêmes calculs pour déterminer la représentation complexe de la similitude envoyant $A$ sur $B$ et $C$ sur $D$, on obtient le même point fixe.
\fincorrection
\finexercice
|
<?php
use App\Accomodation;
use Illuminate\Database\Seeder;
class AccomodationSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$accomodations = [
// ROMA - DAJE!
[
'title' => "Intero alloggio (casa)",
'description' => 'Situato a due passi del centro storico di Roma e dalla Stazione Trastevere questo delizioso loft gode di una location privilegiata che permette di esplorare la città a piedi.',
'number_rooms' => 4,
'number_bathrooms' => 2,
'number_beds' => 2,
'square_mts' => 130,
'price_per_night' => 30,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Muzio Clementi',
'building_number' => 81,
'zip' => '00193',
'lat' => 41.90980,
'lon' => 12.47235,
'placeholder' => "",
'user_id' => 1,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Artists House - CENTRUM - Campo de fiori',
'description' => "Appartamento situato in un palazzo medioevale del 1200. E' stato completamenete ristrutturato, con rifiniture di lusso: wifi, computer, Tv Grande schermo HD, impianto stereo centralizzato, cassaforte a muro.",
'number_rooms' => 5,
'number_bathrooms' => 3,
'number_beds' => 3,
'square_mts' => 120,
'price_per_night' => 40,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => ' Giorgio Perlasca',
'building_number' => 13,
'zip' => '00155',
'lat' => 41.90235,
'lon' => 12.56785,
'placeholder' => "",
'user_id' => 2,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Domus Chiavari House',
'description' => "Situata nell'incantevole quartiere di Campo de Fiori, in uno dei più caratteristici vicoli di Roma, a pochi metri dal Pantheon, Piazza Navona e Piazza Venezia, la Domus Campo de' Fiori offre un grazioso appartamento, finemente decorato e posto al piano terra di un delizioso cortile condominiale. La struttura dispone di angolo cottura attrezzato, macchina da caffè, soggiorno con divano e area dining e bagno con doccia set di cortesia.",
'number_rooms' => 5,
'number_bathrooms' => 3,
'number_beds' => 3,
'square_mts' => 120,
'price_per_night' => 40,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Salaria',
'building_number' => 1223,
'zip' => '00138',
'lat' => 41.992283,
'lon' => 12.51055,
'placeholder' => "",
'user_id' => 3,
'check_in' => 13,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Boheme Cottage with swimming pool',
'description' => "Boheme Cottage si trova nella parte sud di Roma e ha un bel giardino tutto intorno. Nelle vicinanze si trova l'area archeologica del Parco dell'Appia Antica e il Santuario di Santa Maria del Divino Amore. La piscina è aperta da fine maggio a fine settembre",
'number_rooms' => 3,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 120,
'price_per_night' => 68,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Antonio Zanoni',
'building_number' => 51,
'zip' => '00134',
'lat' => 41.47018,
'lon' => 12.514640,
'placeholder' => "",
'user_id' => 4,
'check_in' => 18,
'check_out' => 14,
'count_services' => 0,
],
[
'title' => 'Mini House.',
'description' => "Il mini appartamento, completamente ristrutturato nel 2018, si trova in un piccolo appartamento costruito nel 1930. La sua posizione all'ultimo piano (4 ° piano senza ascensore) garantisce una splendida vista sulla città. È possibile rilassarsi dopo una giornata intensa di visite turistiche. Puoi fare una siesta, bere un bicchiere di vino o goderti il cielo serale sull'amaca colorata sull'enorme terrazza piena di piante di questo arioso appartamento, desiderare di sentirti come un locale dopo lunghe giornate nelle zone turistiche. Molti bei ristoranti frequentati principalmente da gente del posto",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 45,
'price_per_night' => 50,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Luigi Tosti',
'building_number' => 28,
'zip' => '00179',
'lat' => 41.87233,
'lon' => 12.51840,
'placeholder' => "",
'user_id' => 5,
'check_in' => 15,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'Pettinarihome Campo de Fiori',
'description' => "Il nostro appartamento e' una suite di 25 mq. a pochi passi da Campo de Fiori, Ponte Sisto, Piazza Trilussa, Piazza Navona, situato in un palazzetto del 1600, al 3 ed ultimo piano senza ascensore, molto luminoso e tranquillo, la struttura puo' ospitare n 2 persone, la suite e' stata recentemente ristrutturata ed e' fornita di ogni comfort, compreso nel prezzo anche una deliziosa (website hidden) prenotazione possiamo offrire ai nostri clienti un servizio di taxi, dall'Aeroporto al centro di Roma, e viceversa, dal centro di Roma all'Aeroporto di partenza, questo servizio e' esclusivamente per i nostri ospiti. Distanze indicative calcolate in linea d'aria da BED AND BREAKFAST PETTINARIHOME CAMPO DE FIORI, per alcuni punti di grandi dimensioni, sono calcolate dal centro. Clicca sul luogo per vedere il percorso stradale.",
'number_rooms' => 1,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 25,
'price_per_night' => 45,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'dei pettinari',
'building_number' => 53,
'zip' => '00186',
'lat' => 41.892912,
'lon' => 12.471453,
'placeholder' => "",
'user_id' => 1,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Colosseo Corner',
'description' => "COLOSSEO alla tua porta di casa, non può andare meglio di così. Decorato con alcune insegne nostalgiche che completano l'aspetto vintage di questo appartamento.
Davvero perfetto per una coppia e gli amici che cercano una fuga veloce",
'number_rooms' => 4,
'number_bathrooms' => 1,
'number_beds' => 4,
'square_mts' => 80,
'price_per_night' => 115,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'di S.Giovanni Laterano',
'building_number' => 55,
'zip' => '00179',
'lat' => 41.888904,
'lon' => 12.438991,
'placeholder' => "",
'user_id' => 2,
'check_in' => 14,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'La Casa di Monte Giordano 1',
'description' => "L'appartamento si trova nel cuore di Roma, a pochi passi dalle maggiori attrazioni della città. Situato in una delle zone più antiche e storiche. È dotato di tutto il necessario per trascorrere un soggiorno confortevole. Si trova al piano terra di un antico edificio del XVII secolo in una piccola e pittoresca strada, equidistante da Piazza Navona e Castel Sant' Angelo.",
'number_rooms' => 1,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 30,
'price_per_night' => 55,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'di Monte Giordano',
'building_number' => 1,
'zip' => '00186',
'lat' => 41.899433,
'lon' => 12.469845,
'placeholder' => "",
'user_id' => 3,
'check_in' => 16,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Camera zona San Pietro',
'description' => "Camera doppia situata al centro di Roma uso singola con i seguenti servizi en-suite: bagno privato,tv-sat,frigo,aria condizionata,wi-fi, cassaforte, bollitore",
'number_rooms' => 1,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 20,
'price_per_night' => 45,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Viale',
'street_name' => 'Angelico',
'building_number' => 30,
'zip' => '00195',
'lat' => 41.914833,
'lon' => 12.458694,
'placeholder' => "",
'user_id' => 4,
'check_in' => 15,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'Historic center Campo dei Fiori',
'description' => "Ottima posizione nel cuore del centro storico di Roma, situato tra il ghetto ebraico e Campo dei fiori. Si trova in un palazzo storico del 1700 con volte a stella, piano terra, completamente ristrutturato e arredato, zona notte con soppalco di 2 metri, divano soggiorno, riscaldamento autonomo, lavatrice, aria condizionata, wi-fi.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 45,
'price_per_night' => 65,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Arenula',
'building_number' => 26,
'zip' => '00186',
'lat' => 41.893231,
'lon' => 12.475478,
'placeholder' => "",
'user_id' => 5,
'check_in' => 12,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'Casa "Vicolo della Torre" - TRASTEVERE',
'description' => "Trastevere, raffinato Loft nel centro di Roma,
completamente ristrutturato nel 2019.
Finemente arredato, dotato di ogni comodità, caratteristico e funzionale, con entrata indipendente e check-in automatico, ti sentirai libero di godere della vera atmosfera di Roma. La posizione è eccezionale tutti i monumenti più famosi sono raggiungibile a piedi, ma è anche vicino ai mezzi pubblici, market, negozi per lo shopping e pub, qui potrai deliziarti con i menù tipici nelle molteplici osterie romane!",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 50,
'price_per_night' => 85,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Vicolo',
'street_name' => 'della Torre',
'building_number' => 3,
'zip' => '00153',
'lat' => 41.889451,
'lon' => 12.472550,
'placeholder' => "",
'user_id' => 1,
'check_in' => 13,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Colosseo Superior Apartment',
'description' => "Siamo nel cuore di Roma, a pochi passi dal Colosseo e dalla Basilica di San Giovanni in Laterano. Passeggiando si possono comodamente raggiungere molti dei principali luoghi di interesse storico, culturale e di intrattenimento.
Vicinissimo alla metro e a diverse fermate di autobus, situato in una via silenziosa, al riparo dal traffico e dal caos cittadino, vi accogliamo in un edificio indipendente completamente ristrutturato, composto da sei piccoli appartamenti.",
'number_rooms' => 3,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 80,
'price_per_night' => 105,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Domenico Fontana',
'building_number' => 24,
'zip' => '00185',
'lat' => 41.887917,
'lon' => 12.507082,
'placeholder' => "",
'user_id' => 2,
'check_in' => 14,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Casa Villa Statilia 5',
'description' => "Villa Statilia 5 è una stupendo monolocale con bagno, situato al centro di Roma in un luogo comodissimo per visitare la città, ma allo stesso tempo molto tranquillo e silenzioso. Il grande patio esterno attrezzato la rendono un' oasi di pace dove assaporare al meglio l'atmosfera della Città Eterna.
Comodissimo l'uso di una cucina comune, un distributore automatico e la possibilità di affittare in loco delle biciclette.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 45,
'price_per_night' => 75,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Statilia',
'building_number' => 5,
'zip' => '00185',
'lat' => 41.889635,
'lon' => 12.509096,
'placeholder' => "",
'user_id' => 3,
'check_in' => 16,
'check_out' => 12,
'count_services' => 0,
],
[
'title' => 'Green loft Trastevere',
'description' => "Loft nel cuore di Roma zona Trastevere, ottima posizione, intero appartamento a disposizione, self check-in, dotato di tutti i comfort e servizi, cucina, Tv Wi-fi inclusi.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 40,
'price_per_night' => 95,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'dei Panieri',
'building_number' => 48,
'zip' => '00153',
'lat' => 41.890254,
'lon' => 12.466335,
'placeholder' => "",
'user_id' => 4,
'check_in' => 13,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'B&B S.Paolo - stanza blu 2',
'description' => "Stanza blu numero 2: ampia camera di circa 15 metri quadrati nel cuore di Roma al confine tra il il rione Testaccio e la Garbatella. vicino alla Piramide (fermata metro linea B) ed a 10 minuti dal Colosseo-Foro Romano. Colazione inclusa nel prezzo, letto matrimoniale, bagno privato con GRANDE doccia, asciugamani, aria condizionata fresca e calda, WI-FI, TV, mini frigo e GRANDE terrazzo. 2 ospiti massimo. ",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 45,
'price_per_night' => 75,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'dei Conciatori',
'building_number' => 1,
'zip' => '00154',
'lat' => 41.874323,
'lon' => 12.480140,
'placeholder' => "",
'user_id' => 5,
'check_in' => 14,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'Trevi Luxuri - Attico',
'description' => "Appartamento delizioso situato in una tranquilla e storica via a pochi passi dalla magica Fontana di Trevi e dalla famosa Piazza di Spagna. Questo piccolo attico si affaccia sui tetti di Roma e dispone di una terrazzetta dalla quale si può godere di un panorama suggestivo e romantico. Appena ristrutturato l'appartamento dispone di tutti i comfort: wi fi, aria condizionata, riscaldamento, smart tv 50 pollici, cucina attrezzata tavola e ferro da stiro.
Lo spazio
L' appartamento si trova al 5 piano di uno storico e signorile palazzo nel centro di Roma ed è provvisto di ascensore. Grazie al fatto di trovarsi all ultimo piano e di disporre di ampie finestre, l 'appartamento è estremamente luminoso.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 60,
'price_per_night' => 100,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'del Lavoratore',
'building_number' => 30,
'zip' => '00187',
'lat' => 41.901302,
'lon' => 12.484814,
'placeholder' => "",
'user_id' => 1,
'check_in' => 13,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'Graziosa mansarda con vista sul Pantheon',
'description' => "Pittoresca mansarda con travi a vista e magnifico affaccio sulla piazza del Pantheon, nel cuore di Roma, composta da camera con letto matrimoniale, smart tv e aria condizionata; seconda stanza con cucina e divano letto per 1 adulto o 2 bambini (larghezza 140 cm.); bagno con doccia.
Materasso e cuscini confortevoli.
L'appartamento è dotato di WI-FI, lavatrice, stendibiancheria, ferro e asse da stiro, frigo con piccolo freezer, forno a micronde e tutto il necessario per cucinare.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 55,
'price_per_night' => 85,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Piazza',
'street_name' => 'Capranica',
'building_number' => 72,
'zip' => '00186',
'lat' => 41.899981,
'lon' => 12.477889,
'placeholder' => "",
'user_id' => 2,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => 'Happy Giulia',
'description' => "Situato nello storico quartiere popolare di San Lorenzo, questo caratteristico bilocale si trova a 10 minuti a piedi dalla stazione Termini, Basilica di San Giovanni, Basilica di Santa Maria Maggiore, Piazza Vittorio, Terme di Diocleziano, Palazzo delle Esposizioni, Rione Monti e altro ancora. L'appartamento offre una discreta tranquillità, pur trovandosi in un quartiere giovane, vicino alla città universitaria, ricco di vita notturna, locali alla moda, cucina tipica e varietà di locali da pranzo.",
'number_rooms' => 3,
'number_bathrooms' => 1,
'number_beds' => 3,
'square_mts' => 55,
'price_per_night' => 75,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'Livorno',
'building_number' => 5,
'zip' => '00162',
'lat' => 41.914600,
'lon' => 12.521859,
'placeholder' => "",
'user_id' => 3,
'check_in' => 15,
'check_out' => 12,
'count_services' => 0,
],
[
'title' => 'Bilocale Roma - ghetto ebraico',
'description' => "Ghetto Ebraico, piano terra, bilocale 40 mq, salone e camera letto, soffitto a cassettoni e cotto, completamente ristrutturato e arredato, piastra induzione, lavatrice, piccolo bagno con doccia, aria condizionata, wi-fi.",
'number_rooms' => 4,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 45,
'price_per_night' => 75,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Piazza',
'street_name' => 'Benedetto Cairoli',
'building_number' => 5,
'zip' => '00186',
'lat' => 41.893889,
'lon' => 12.475148,
'placeholder' => "",
'user_id' => 4,
'check_in' => 16,
'check_out' => 14,
'count_services' => 0,
],
[
'title' => 'Colosseo Design Apartment',
'description' => "Questo appartamento elegante e moderno si trova a soli 5 minuti a piedi dal Colosseo e dal Foro Romano e dispone dei servizi alberghieri più elevati.",
'number_rooms' => 5,
'number_bathrooms' => 2,
'number_beds' => 3,
'square_mts' => 105,
'price_per_night' => 185,
'visibility' => true,
'country' => 'Italy',
'city' => 'Roma',
'province' => 'Roma',
'type_street' => 'Via',
'street_name' => 'degli Annibaldi',
'building_number' => 8,
'zip' => '00162',
'lat' => 41.892469,
'lon' => 12.491732,
'placeholder' => "",
'user_id' => 5,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
// MILANO - Ape sui navigli TAC!!
[
'title' => 'Intero alloggio',
'description' => "Elegante appartamento di 90mq in Piazza Tommaseo, a pochi passi dalla stazione metropolitana Conciliazione (linea MM1 - rossa), in un quartiere aristocratico nel pieno centro di Milano.",
'number_rooms' => 5,
'number_bathrooms' => 2,
'number_beds' => 1,
'square_mts' => 90,
'price_per_night' => 150,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Piazza',
'street_name' => 'Nicolò Tommaseo',
'building_number' => 2,
'zip' => '20123',
'lat' => 45.469776,
'lon' => 9.166800,
'placeholder' => "",
'user_id' => 1,
'check_in' => 16,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => 'Intero alloggio',
'description' => "Accogliente monolocale sui Navigli, perfetto per chi vuole visitare Milano. Appena ristrutturato, l'appartamento è in posizione centrale e a pochi passi dal Duomo. La zona è ricca di ristoranti e locali caratteristici per vivere al meglio la città. Ideale per gli studenti degli istituti NABA (distante letteralmente 3 minuti a piedi), IULM e Bocconi.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 4,
'square_mts' => 90,
'price_per_night' => 70,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => "dell'Orso",
'building_number' => 7,
'zip' => '20121',
'lat' => 45.4724691,
'lon' => 9.1861503,
'placeholder' => "",
'user_id' => 2,
'check_in' => 14,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => "PrimoPiano - XXII Marzo",
'description' => "Loft in contesto ex industriale con posto auto. Living room con zona pranzo, piccola cucina, bagno, soppalco con zona notte.",
'number_rooms' => 6,
'number_bathrooms' => 5,
'number_beds' => 9,
'square_mts' => 100,
'price_per_night' => 135,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Arcangelo Corelli',
'building_number' => 56,
'zip' => '20134',
'lat' => 45.47319,
'lon' => 9.25395,
'placeholder' => "",
'user_id' => 3,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Loft Garden",
'description' => "Soggiornare a pochi passi dal Duomo di Milano, cattedrale simbolo della città e uno dei monumenti più belli e suggestivi al mondo in appartamenti di ricercato design, completi di tutte le comodità possibili per rendere il vostro soggiorno speciale e vivere un sogno a occhi aperti.",
'number_rooms' => 7,
'number_bathrooms' => 4,
'number_beds' => 4,
'square_mts' => 90,
'price_per_night' => 115,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Caldera',
'building_number' => 3,
'zip' => '20153',
'lat' => 45.480654,
'lon' => 9.1040962,
'placeholder' => "",
'user_id' => 4,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Villetta a schiera",
'description' => "Una deliziosa villeta a schiera in stile moderno, perfetta per coppie e famiglie.",
'number_rooms' => 4,
'number_bathrooms' => 2,
'number_beds' => 3,
'square_mts' => 120,
'price_per_night' => 105,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Alessandro Litta',
'building_number' => 93,
'zip' => '20161',
'lat' => 45.52176,
'lon' => 9.15377,
'placeholder' => "",
'user_id' => 5,
'check_in' => 14,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => "Casa di design in zona centrale",
'description' => "Grazioso piccolo loft al secondo piano di una caratteristica casa di ringhiera milanese, silenziosa e accogliente.
Ottima posizione a 5 min a piedi dalla Stazione centrale. Si trova a due passi da Piazza Gae Aulenti (Corso Como), dal Duomo di Milano, Isola, Corso Buenos Aires,Porta Venezia.",
'number_rooms' => 3,
'number_bathrooms' => 1,
'number_beds' => 3,
'square_mts' => 55,
'price_per_night' => 85,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Alfredo Campanini',
'building_number' => 6,
'zip' => '20124',
'lat' => 45.48607,
'lon' => 9.19822,
'placeholder' => "",
'user_id' => 1,
'check_in' => 13,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Cozy Apartment Blue",
'description' => "Grazioso appartamento Situato in zona Stazione Centrale/ Corso Buenos Aires, a pochi passi dalla stazione e pochi minuti dal centro, comoda per i servizi e mezzi nelle vicinanze.
Contesto signorile con portineria
Appartamento al piano terra, recentemente ristrutturato, completamente arredato e dotato di tutti i confort (lavatrice, biancheria casa, TV, macchina del caffè, Asciugacapelli, Wifii…)
Perfetta sia per Visitare la città di Milano sia per viaggi di lavoro.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 60,
'price_per_night' => 90,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Tonale',
'building_number' => 24,
'zip' => '20125',
'lat' => 45.48964,
'lon' => 9.20179,
'placeholder' => "",
'user_id' => 2,
'check_in' => 13,
'check_out' => 11,
'count_services' => 0,
],
[
'title' => "PrimoPiano - Gluck Flat",
'description' => "Ampio monolocale attrezzato con TV, internet WiFi, cucina a parete, divano letto e bagno con doccia.",
'number_rooms' => 1,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 30,
'price_per_night' => 65,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Cristoforo Gluck',
'building_number' => 37,
'zip' => '20125',
'lat' => 45.493424,
'lon' => 9.208948,
'placeholder' => "",
'user_id' => 3,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Ampio bilocale - Stazione Centrale",
'description' => "SELF CHECK-IN APERTURA PORTE CON CELLULARE dalle 15:00, check-out entro le 10:00. Luminoso ampio bilocale a 5 minuti a piedi da Stazione Centrale. Stanza da letto con 1 letto matrimoniale, soggiorno con un divano letto 2 piazze. Aria condizionata, Wi-fi 200mb, SmartTV.
[CIR: 015146-CNI-00438]",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 90,
'price_per_night' => 100,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Gianfranco Zuretti',
'building_number' => 23,
'zip' => '20125',
'lat' => 45.49311,
'lon' => 9.20727,
'placeholder' => "",
'user_id' => 4,
'check_in' => 15,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "La casa sui tetti",
'description' => "Godetevi questo silenzioso appartamento situato in uno dei quartieri più caratteristici e pulp di Milano. Arredato in modo funzionale e ideale per qualsiasi tipologia di viaggiatore, offre un ottimo spazio anche per necessità di homeworking.
Moderno, elegante e tranquillo, si trova in una posizione strategica sia che siate a Milano per affari che per puro svago.
Situato a pochi passi dalla Stazione Centrale e a 3 min da Corso Buenos Aires e Piazza Gae Aulenti.",
'number_rooms' => 1,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 30,
'price_per_night' => 65,
'visibility' => true,
'country' => 'Italy',
'city' => 'Milano',
'province' => 'Milano',
'type_street' => 'Via',
'street_name' => 'Napo Torriani',
'building_number' => 9,
'zip' => '20124',
'lat' => 45.4841446,
'lon' => 9.20331,
'placeholder' => "",
'user_id' => 5,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
// VENEZIA - OSTREGHETA!
[
'title' => "La casa degli Angeli",
'description' => "Lo spazio è costituito da un grande monolocale con cucina e bagno..per dormire c è un divano letto molto comodo..lo spazio è munito di condizionatore...pala e ventilatore..due televisioni e lavatrice.",
'number_rooms' => 6,
'number_bathrooms' => 3,
'number_beds' => 5,
'square_mts' => 70,
'price_per_night' => 55,
'visibility' => true,
'country' => 'Italy',
'city' => 'Venezia',
'province' => 'Venezia',
'type_street' => 'Piazza',
'street_name' => '27 Ottobre',
'building_number' => 91,
'zip' => '30172',
'lat' => 45.4952676,
'lon' => 12.242072,
'placeholder' => "",
'user_id' => 1,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Intero alloggio: unità in affitto",
'description' => "Il soffitto dell'appartamento è il tipico soffitto veneziano con i travi in legno a vista. Il parquet di legno bianco fa risaltare gli spazi e la luminosità dell'appartamento. L'appartamento è stato arredato e restaurato di recente. La zona in cui è ubicato l'appartamento è molto caratteristica e centrale. ",
'number_rooms' => 6,
'number_bathrooms' => 3,
'number_beds' => 5,
'square_mts' => 70,
'price_per_night' => 55,
'visibility' => true,
'country' => 'Italy',
'city' => 'Venezia',
'province' => 'Venezia',
'type_street' => 'Piazza',
'street_name' => 'Campo Santa Maria del Giglio',
'building_number' => 2494,
'zip' => '30124',
'lat' => 45.43509,
'lon' => 12.332401,
'placeholder' => "",
'user_id' => 2,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Venezia... esageratamente Venezia!",
'description' => "Il soffitto dell'appartamento è il tipico soffitto veneziano con i travi in legno a vista. Il parquet di legno bianco fa risaltare gli spazi e la luminosità dell'appartamento. L'appartamento è stato arredato e restaurato di recente. La zona in cui è ubicato l'appartamento è molto caratteristica e centrale. A solo qualche minuto a piedi si raggiunge il famosissimo Ponte di Rialto e attraversandolo si arriva nell'area del Mercato del Pesce e delle Osterie.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 70,
'price_per_night' => 65,
'visibility' => true,
'country' => 'Italy',
'city' => 'Venezia',
'province' => 'Venezia',
'type_street' => 'Calle',
'street_name' => 'de la Bissa',
'building_number' => 1,
'zip' => '30124',
'lat' => 45.438325,
'lon' => 12.337059,
'placeholder' => "",
'user_id' => 3,
'check_in' => 15,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Spacious with stunning views!",
'description' => "Appartamento molto spazioso, luminoso e restaurato nel quartiere più locale di Venezia. Da ogni finestra è possibile gettare uno sguardo sui tetti, un ampio canale e un giardino. In pochi minuti a piedi troverai i punti salienti della città ei ristoranti migliori e più economici di Venezia. L'appartamento è situato tra la stazione ferroviaria/terminal delle auto e Piazza San Marco.
È molto facile raggiungerlo, non importa come si arriva a Venezia (la fermata del vaporetto è a soli 4 minuti di distanza).",
'number_rooms' => 4,
'number_bathrooms' => 1,
'number_beds' => 5,
'square_mts' => 110,
'price_per_night' => 155,
'visibility' => true,
'country' => 'Italy',
'city' => 'Venezia',
'province' => 'Venezia',
'type_street' => 'Calle',
'street_name' => 'dei Riformati',
'building_number' => 3213,
'zip' => '30121',
'lat' => 45.447199,
'lon' => 12.326657,
'placeholder' => "",
'user_id' => 4,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Floating house in the authentic Venice",
'description' => "Appartamento romantico con una vista unica. Nuovo ed elegante questo è il loft ideale per una coppia o una famiglia che vuole vivere il sogno romantico di Venezia con una vista unica e meravigliosa del Canal e della Gondola di Venezia. L'appartamento è riservato, silenzioso, spazioso e confortevole e si trova in un autentico e tipico quartiere veneziano ricco di ristoranti, bar, negozi frequentati dai veneziani vicino alla stazione, ai vaporetti e ai principali punti di interesse Rialto e Piazza San Marco",
'number_rooms' => 4,
'number_bathrooms' => 1,
'number_beds' => 3,
'square_mts' => 85,
'price_per_night' => 95,
'visibility' => true,
'country' => 'Italy',
'city' => 'Venezia',
'province' => 'Venezia',
'type_street' => 'Calle',
'street_name' => 'Groppi',
'building_number' => 2543,
'zip' => '30121',
'lat' => 45.444931,
'lon' => 12.332019,
'placeholder' => "",
'user_id' => 5,
'check_in' => 14,
'check_out' => 12,
'count_services' => 0,
],
// FIRENZE - La Coha Hola hon la hannuccia horta horta!
[
'title' => "Ampia stanza",
'description' => "Ampia stanza di 25 mq con ingresso indipendente e bagno privato al primo piano di un antico edificio del centro storico, a 200 metri da Piazza della Signoria, Uffizi e Piazza Santa Croce.
A pochi passi si trovano molti ristoranti tipici e negozi. La via è molto tranquilla e l'affaccio della stanza su una corte interna la rende particolarmente silenziosa.",
'number_rooms' => 1,
'number_bathrooms' => 1,
'number_beds' => 2,
'square_mts' => 25,
'price_per_night' => 68,
'visibility' => true,
'country' => 'Italy',
'city' => 'Firenze',
'province' => 'Firenze',
'type_street' => 'Via',
'street_name' => 'degli Orti Oricellari',
'building_number' => 30,
'zip' => '50123',
'lat' => 43.784229,
'lon' => 11.2480423,
'placeholder' => "",
'user_id' => 1,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "La casa degli Angeli",
'description' => "Lo spazio è costituito da un grande monolocale con cucina e bagno..per dormire c è un divano letto molto comodo..lo spazio è munito di condizionatore...pala e ventilatore..due televisioni e lavatrice.",
'number_rooms' => 3,
'number_bathrooms' => 2,
'number_beds' => 3,
'square_mts' => 40,
'price_per_night' => 87,
'visibility' => true,
'country' => 'Italy',
'city' => 'Firenze',
'province' => 'Firenze',
'type_street' => 'Via',
'street_name' => 'Giulio Caccini',
'building_number' => 24,
'zip' => '50141',
'lat' => 43.80690,
'lon' => 11.24392,
'placeholder' => "",
'user_id' => 2,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Vigna Vecchia Modern Studio",
'description' => "Moderno monolocale di 15mq in grado di ospitare fino a due persone. Collocato al secondo piano (senza ascensore) di uno stabile antico in buone condizioni, l'alloggio si trova in zona Santa Croce, posizione ideale per visitare al meglio la città di Firenze e tutti i principali punti di interesse. Siamo a 5 minuti di distanza a piedi da Piazza della Signoria e 10 da Ponte Vecchio.",
'number_rooms' => 3,
'number_bathrooms' => 2,
'number_beds' => 3,
'square_mts' => 40,
'price_per_night' => 87,
'visibility' => true,
'country' => 'Italy',
'city' => 'Firenze',
'province' => 'Firenze',
'type_street' => 'Via',
'street_name' => 'Maragliano',
'building_number' => 69,
'zip' => '50144',
'lat' => 43.78844,
'lon' => 11.23312,
'placeholder' => "",
'user_id' => 3,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Maggio Tower View",
'description' => "Loft prestigioso situato a Firenze in zona Oltrarno, con vista mozzafiato a 360 gradi su tutti i monumenti fiorentini. Ideale per affitti di breve periodo. Ambiente unico, composto di zona salotto, zona notte, bagno completo, angolo cucina. Può ospitare 2 persone.",
'number_rooms' => 2,
'number_bathrooms' => 1,
'number_beds' => 1,
'square_mts' => 65,
'price_per_night' => 93,
'visibility' => true,
'country' => 'Italy',
'city' => 'Firenze',
'province' => 'Firenze',
'type_street' => 'Via',
'street_name' => 'Maragliano',
'building_number' => 69,
'zip' => '50144',
'lat' => 43.78844,
'lon' => 11.23312,
'placeholder' => "",
'user_id' => 4,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
[
'title' => "Vigna Vecchia Modern Studio",
'description' => "Moderno monolocale di 15mq in grado di ospitare fino a due persone. Collocato al secondo piano (senza ascensore) di uno stabile antico in buone condizioni, l'alloggio si trova in zona Santa Croce, posizione ideale per visitare al meglio la città di Firenze e tutti i principali punti di interesse. Siamo a 5 minuti di distanza a piedi da Piazza della Signoria e 10 da Ponte Vecchio.",
'number_rooms' => 3,
'number_bathrooms' => 2,
'number_beds' => 3,
'square_mts' => 40,
'price_per_night' => 87,
'visibility' => true,
'country' => 'Italy',
'city' => 'Firenze',
'province' => 'Firenze',
'type_street' => 'Via',
'street_name' => 'Maragliano',
'building_number' => 69,
'zip' => '50144',
'lat' => 43.78844,
'lon' => 11.23312,
'placeholder' => "",
'user_id' => 5,
'check_in' => 12,
'check_out' => 10,
'count_services' => 0,
],
];
foreach ($accomodations as $accomodation) {
$new_accomodation = new Accomodation();
$new_accomodation->fill($accomodation);
$new_accomodation->save();
}
}
}
|
<!DOCTYPE html>
<html>
<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 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<script>
function CalcBill() {
var a = parseInt(document.getElementById('price1').value);
var b = parseInt(document.getElementById('price2').value);
var c = parseInt(document.getElementById('price3').value);
var d = parseInt(document.getElementById('price4').value);
var sum = (a * 500) + (b * 300) + (c * 400) + (d * 250);
var elem = document.getElementById('result');
elem.innerHTML = sum;
}
</script>
</head>
<body>
<div class="titleBox">
CAKE SHOP
</div>
<div class="cakeImages">
<div class="imageBox">
<img src="Cake1.png" class="cake">
Funfetti Cake - Rs. 500
</div>
<div class="imageBox">
<img src="Cake2.png" class="cake">
Color Cake - Rs. 300
</div>
<div class="imageBox">
<img src="Cake3.png" class="cake">
Chocolate Cake - Rs. 400
</div>
<div class="imageBox">
<img src="Cake4.png" class="cake">
Strawberry Cake - Rs. 250
</div>
</div>
<div class="space"><br><br></div>
<div class="orderTitle">
ORDER CAKE
</div>
<div class="form">
<div class="d-flex d-inline row w-25">
<form class="p-2">
<div class="form-group">
<label>Funfetti Cake:</label>
<input type="number" class="form-control" placeholder="Quanity" id="price1">
</div>
<div class="form-group">
<label>Color Cake</label>
<input type="number" class="form-control" placeholder="Quanity" id="price2">
</div>
<div class="form-group">
<label>Chocolate Cake</label>
<input type="number" class="form-control" placeholder="Quanity" id="price3">
</div>
<div class="form-group">
<label>Strawberry Cake</label>
<input type="number" class="form-control" placeholder="Quanity" id="price4">
</div>
</form>
<div class="orderButton" onclick="CalcBill()">
<button type="submit" class="d-flex mt-4 btn btn-primary w-50 justify-content-center">Place Order</button>
</div>
</div>
</div>
<div class="space">
<br>
</div>
<div class="billText">
Purchase Order Bill!!
</div>
<div class="finalBill">
<div class="totalPriceBox">
Total Price
</div>
<div class="result" id="result">
</div>
</div>
<div>
<br>
<br>
<br>
<br>
</div>
</body>
<body>
</body>
</html>
|
using Microsoft.Xna.Framework;
using Monocle;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Celeste
{
public class Strawberry : Entity
{
public static ParticleType P_Glow;
public static ParticleType P_GhostGlow;
public static ParticleType P_GoldGlow;
public static ParticleType P_MoonGlow;
public static ParticleType P_WingsBurst;
public EntityID ID;
private Sprite sprite;
public Follower Follower;
private Wiggler wiggler;
private Wiggler rotateWiggler;
private BloomPoint bloom;
private VertexLight light;
private Tween lightTween;
private float wobble;
private Vector2 start;
private float collectTimer;
private bool collected;
private readonly bool isGhostBerry;
private bool flyingAway;
private float flapSpeed;
public bool ReturnHomeWhenLost = true;
public bool WaitingOnSeeds;
public List<StrawberrySeed> Seeds;
public bool Winged { get; private set; }
public bool Golden { get; private set; }
public bool Moon { get; private set; }
private string gotSeedFlag => "collected_seeds_of_" + ID.ToString();
public Strawberry(EntityData data, Vector2 offset, EntityID gid)
{
ID = gid;
Position = start = data.Position + offset;
Winged = data.Bool("winged") || data.Name == "memorialTextController";
Golden = data.Name is "memorialTextController" or "goldenBerry";
Moon = data.Bool("moon");
isGhostBerry = SaveData.Instance.CheckStrawberry(ID);
Depth = -100;
Collider = new Hitbox(14f, 14f, -7f, -7f);
Add(new PlayerCollider(new Action<Player>(OnPlayer)));
Add(new MirrorReflection());
Add(Follower = new Follower(ID, onLoseLeader: new Action(OnLoseLeader)));
Follower.FollowDelay = 0.3f;
if (Winged)
Add(new DashListener()
{
OnDash = new Action<Vector2>(OnDash)
});
if (data.Nodes == null || data.Nodes.Length == 0)
return;
Seeds = new List<StrawberrySeed>();
for (int index = 0; index < data.Nodes.Length; ++index)
Seeds.Add(new StrawberrySeed(this, offset + data.Nodes[index], index, isGhostBerry));
}
public override void Added(Scene scene)
{
base.Added(scene);
if (SaveData.Instance.CheckStrawberry(ID))
{
sprite = !Moon ? (!Golden ? GFX.SpriteBank.Create("ghostberry") : GFX.SpriteBank.Create("goldghostberry")) : GFX.SpriteBank.Create("moonghostberry");
sprite.Color = Color.White * 0.8f;
}
else
sprite = !Moon ? (!Golden ? GFX.SpriteBank.Create("strawberry") : GFX.SpriteBank.Create("goldberry")) : GFX.SpriteBank.Create("moonberry");
Add(sprite);
if (Winged)
sprite.Play("flap");
sprite.OnFrameChange = new Action<string>(OnAnimate);
Add(wiggler = Wiggler.Create(0.4f, 4f, v => sprite.Scale = Vector2.One * (float)(1.0 + (double)v * 0.34999999403953552)));
Add(rotateWiggler = Wiggler.Create(0.5f, 4f, v => sprite.Rotation = (float)((double)v * 30.0 * (Math.PI / 180.0))));
Add(bloom = new BloomPoint(Golden || Moon || isGhostBerry ? 0.5f : 1f, 12f));
Add(light = new VertexLight(Color.White, 1f, 16, 24));
Add(lightTween = light.CreatePulseTween());
if (Seeds != null && Seeds.Count > 0 && !(scene as Level).Session.GetFlag(gotSeedFlag))
{
foreach (StrawberrySeed seed in Seeds)
scene.Add(seed);
Visible = false;
Collidable = false;
WaitingOnSeeds = true;
bloom.Visible = light.Visible = false;
}
if ((scene as Level).Session.BloomBaseAdd <= 0.10000000149011612)
return;
bloom.Alpha *= 0.5f;
}
public override void Update()
{
if (WaitingOnSeeds)
return;
if (!collected)
{
if (!Winged)
{
wobble += Engine.DeltaTime * 4f;
sprite.Y = bloom.Y = light.Y = (float) Math.Sin(wobble) * 2f;
}
int followIndex = Follower.FollowIndex;
if (Follower.Leader != null && Follower.DelayTimer <= 0.0 && IsFirstStrawberry)
{
bool flag = false;
if (Follower.Leader.Entity is Player entity && entity.Scene != null && !entity.StrawberriesBlocked)
{
if (Golden)
{
if (entity.CollideCheck<GoldBerryCollectTrigger>() || (Scene as Level).Completed)
flag = true;
}
else if (entity.OnSafeGround && (!Moon || entity.StateMachine.State != 13))
flag = true;
}
if (flag)
{
collectTimer += Engine.DeltaTime;
if (collectTimer > 0.15000000596046448)
OnCollect();
}
else
collectTimer = Math.Min(collectTimer, 0.0f);
}
else
{
if (followIndex > 0)
collectTimer = -0.15f;
if (Winged)
{
Y += flapSpeed * Engine.DeltaTime;
if (flyingAway)
{
if ((double) Y < SceneAs<Level>().Bounds.Top - 16)
RemoveSelf();
}
else
{
flapSpeed = Calc.Approach(flapSpeed, 20f, 170f * Engine.DeltaTime);
if ((double) Y < start.Y - 5.0)
Y = start.Y - 5f;
else if ((double) Y > start.Y + 5.0)
Y = start.Y + 5f;
}
}
}
}
base.Update();
if (Follower.Leader == null || !Scene.OnInterval(0.08f))
return;
ParticleType type = !isGhostBerry ? (!Golden ? (!Moon ? Strawberry.P_Glow : Strawberry.P_MoonGlow) : Strawberry.P_GoldGlow) : Strawberry.P_GhostGlow;
SceneAs<Level>().ParticlesFG.Emit(type, Position + Calc.Random.Range(-Vector2.One * 6f, Vector2.One * 6f));
}
private void OnDash(Vector2 dir)
{
if (flyingAway || !Winged || WaitingOnSeeds)
return;
Depth = -1000000;
Add(new Coroutine(FlyAwayRoutine()));
flyingAway = true;
}
private bool IsFirstStrawberry
{
get
{
for (int index = Follower.FollowIndex - 1; index >= 0; --index)
{
if (Follower.Leader.Followers[index].Entity is Strawberry entity && !entity.Golden)
return false;
}
return true;
}
}
private void OnAnimate(string id)
{
if (!flyingAway && id == "flap" && sprite.CurrentAnimationFrame % 9 == 4)
{
Audio.Play("event:/game/general/strawberry_wingflap", Position);
flapSpeed = -50f;
}
if (sprite.CurrentAnimationFrame != (!(id == "flap") ? (!Golden ? (!Moon ? 35 : 30) : 30) : 25))
return;
lightTween.Start();
if (!collected && (CollideCheck<FakeWall>() || CollideCheck<Solid>()))
{
Audio.Play("event:/game/general/strawberry_pulse", Position);
SceneAs<Level>().Displacement.AddBurst(Position, 0.6f, 4f, 28f, 0.1f);
}
else
{
Audio.Play("event:/game/general/strawberry_pulse", Position);
SceneAs<Level>().Displacement.AddBurst(Position, 0.6f, 4f, 28f, 0.2f);
}
}
public void OnPlayer(Player player)
{
if (Follower.Leader != null || collected || WaitingOnSeeds)
return;
ReturnHomeWhenLost = true;
if (Winged)
{
Level level = SceneAs<Level>();
Winged = false;
sprite.Rate = 0.0f;
Alarm.Set(this, Follower.FollowDelay, () =>
{
sprite.Rate = 1f;
sprite.Play("idle");
level.Particles.Emit(Strawberry.P_WingsBurst, 8, Position + new Vector2(8f, 0.0f), new Vector2(4f, 2f));
level.Particles.Emit(Strawberry.P_WingsBurst, 8, Position - new Vector2(8f, 0.0f), new Vector2(4f, 2f));
});
}
if (Golden)
(Scene as Level).Session.GrabbedGolden = true;
Audio.Play(isGhostBerry ? "event:/game/general/strawberry_blue_touch" : "event:/game/general/strawberry_touch", Position);
player.Leader.GainFollower(Follower);
wiggler.Start();
Depth = -1000000;
}
public void OnCollect()
{
if (collected)
return;
int collectIndex = 0;
collected = true;
if (Follower.Leader != null)
{
Player entity = Follower.Leader.Entity as Player;
collectIndex = entity.StrawberryCollectIndex;
++entity.StrawberryCollectIndex;
entity.StrawberryCollectResetTimer = 2.5f;
Follower.Leader.LoseFollower(Follower);
}
if (Moon)
Achievements.Register(Achievement.WOW);
SaveData.Instance.AddStrawberry(ID, Golden);
Session session = (Scene as Level).Session;
session.DoNotLoad.Add(ID);
session.Strawberries.Add(ID);
session.UpdateLevelStartDashes();
Add(new Coroutine(CollectRoutine(collectIndex)));
}
private IEnumerator FlyAwayRoutine()
{
Strawberry strawberry = this;
strawberry.rotateWiggler.Start();
strawberry.flapSpeed = -200f;
Tween tween1 = Tween.Create(Tween.TweenMode.Oneshot, Ease.CubeOut, 0.25f, true);
// ISSUE: reference to a compiler-generated method
tween1.OnUpdate = delegate (Tween t)
{
flapSpeed = MathHelper.Lerp(-200f, 0f, t.Eased);
};
strawberry.Add(tween1);
yield return 0.1f;
Audio.Play("event:/game/general/strawberry_laugh", strawberry.Position);
yield return 0.2f;
if (!strawberry.Follower.HasLeader)
Audio.Play("event:/game/general/strawberry_flyaway", strawberry.Position);
Tween tween2 = Tween.Create(Tween.TweenMode.Oneshot, duration: 0.5f, start: true);
// ISSUE: reference to a compiler-generated method
tween2.OnUpdate = delegate (Tween t)
{
flapSpeed = MathHelper.Lerp(0f, -200f, t.Eased);
};
strawberry.Add(tween2);
}
private IEnumerator CollectRoutine(int collectIndex)
{
Strawberry strawberry = this;
Scene scene = strawberry.Scene;
strawberry.Tag = (int) Tags.TransitionUpdate;
strawberry.Depth = -2000010;
int num = 0;
if (strawberry.Moon)
num = 3;
else if (strawberry.isGhostBerry)
num = 1;
else if (strawberry.Golden)
num = 2;
Audio.Play("event:/game/general/strawberry_get", strawberry.Position, "colour", num, "count", collectIndex);
Input.Rumble(RumbleStrength.Medium, RumbleLength.Medium);
strawberry.sprite.Play("collect");
while (strawberry.sprite.Animating)
yield return null;
strawberry.Scene.Add(new StrawberryPoints(strawberry.Position, strawberry.isGhostBerry, collectIndex, strawberry.Moon));
strawberry.RemoveSelf();
}
private void OnLoseLeader()
{
if (collected || !ReturnHomeWhenLost)
return;
Alarm.Set(this, 0.15f, () =>
{
Vector2 vector = (start - Position).SafeNormalize();
float val = Vector2.Distance(Position, start);
float num = Calc.ClampedMap(val, 16f, 120f, 16f, 96f);
SimpleCurve curve = new(Position, start, start + vector * 16f + vector.Perpendicular() * num * Calc.Random.Choose<int>(1, -1));
Tween tween = Tween.Create(Tween.TweenMode.Oneshot, Ease.SineOut, MathHelper.Max(val / 100f, 0.4f), true);
tween.OnUpdate = f => Position = curve.GetPoint(f.Eased);
tween.OnComplete = f => Depth = 0;
Add(tween);
});
}
public void CollectedSeeds()
{
WaitingOnSeeds = false;
Visible = true;
Collidable = true;
bloom.Visible = light.Visible = true;
(Scene as Level).Session.SetFlag(gotSeedFlag);
}
}
}
|
"use strict";
$(function() {
var token= "b716c2d7a00b44b88cf0c8600d92505b";
var client, streamClient;
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
if (streamClient) {
streamClient.close();
}
client = new ApiAi.ApiAiClient({accessToken: token, streamClientClass: ApiAi.ApiAiStreamClient});
streamClient = client.createStreamClient();
console.log(client.createStreamClient());
streamClient.init();
streamClient.onInit = function() {
console.log("> ON INIT use direct assignment property");
streamClient.open();
};
streamClient.onStartListening = function() {
console.log("> ON START LISTENING");
};
streamClient.onStopListening = function() {
console.log("> ON STOP LISTENING");
};
streamClient.onOpen = function() {
console.log("> ON OPEN SESSION");
};
streamClient.onClose = function() {
console.log("> ON CLOSE");
streamClient.close();
};
streamClient.onResults = streamClientOnResults;
streamClient.onError = function(code, data) {
streamClient.close();
console.log("> ON ERROR", code, data);
};
streamClient.onEvent = function(code, data) {
console.log("> ON EVENT", code, data);
};
function streamClientOnResults(results) {
console.log("> ON RESULTS", results);
}
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
var agentState= {};
function notifyMe(data) {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else if(agentState){
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: data
});
notification.onclick = function () {
window.open("http://localhost:3000");
};
}
}
function sendText(text) {
return client.textRequest(text);
}
function tts(text) {
return client.ttsRequest(text);
}
function startMic() {
streamClient.startListening();
}
function stopMic() {
streamClient.stopListening();
}
// Initialize varibles
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
$window.on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
agentState = false;
break;
case "focus":
agentState = true;
break;
}
}
$(this).data("prevType", e.type);
});
var socket = io();
setBotName();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant" ;
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
//Add Chat bot
function setBotName(){
username= "Alexa";
socket.emit('add user', username);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
function sendMessageByBot(message){
message=cleanInput(message);
addChatMessage({
username: "Alexa",
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message by bot', message);
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
sendText(message)
.then(function(response) {
var result;
try {
result = response.result.fulfillment.speech
} catch(error) {
result = "";
}
//setResponseJSON(response);
console.log(result);
sendMessageByBot(result);
//setResponseOnNode(result, responseNode);
})
.catch(function(err) {
//setResponseJSON(err);
//setResponseOnNode("Something goes wrong", responseNode);
console.log("Error",err);
});
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv ='';
if(typeof data.message === 'string'){
$messageBodyDiv = $('<span class="messageBody">').text(data.message);
}
else
{
$messageBodyDiv = $('<span class="messageBody">').text(JSON.stringify(data.message));
$messageBodyDiv = data.message.map(function(x){
var str = `<span class="messageBody">
<img src=`+x.subpods[0].image+`></img>
</span><br/>`
return str;
});
}
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username && username!=="Alexa") {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Kunal.Rai Chat – ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
socket.on('search', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
notifyMe(data.username + ' joined');
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
notifyMe(data.username + ' left');
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
document.title = data.username + ' typing...';
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
document.title ='Kunal let\'s talk app';
});
});
|
/*
* Copyright (C) 2020 Jordi Sánchez
* This file is part of CPM Hub
*
* 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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <cest/cest.h>
#include <users/UsersRepositoryInMemory.h>
using namespace cest;
describe("Users repository in memory", []() {
it("adds a user to the repository", []() {
UsersRepositoryInMemory repository;
User user("");
repository.add(user);
});
it("user does not exist in repository when it hasn't been stored", []() {
UsersRepositoryInMemory repository;
expect(repository.exists("pepito")).toBe(false);
});
it("user exists in repository after it has been stored", []() {
UsersRepositoryInMemory repository;
User user("pepito");
repository.add(user);
expect(repository.exists("pepito")).toBe(true);
});
it("doesn't find a user when it's not stored", []() {
UsersRepositoryInMemory repository;
Maybe<User> user;
user = repository.find("pepito");
expect(user.isPresent()).toBe(false);
});
it("finds a user after it has been stored stored", []() {
UsersRepositoryInMemory repository;
User user("pepito");
Maybe<User> user_found;
repository.add(user);
user_found = repository.find("pepito");
expect(user_found.isPresent()).toBe(true);
expect(user_found.value().name).toBe("pepito");
});
});
|
<template>
<div class="app-container">
<div>
<el-form ref="form" :model="form" class="form">
<el-form-item>
<el-col :span="5">
<el-input v-model="form.username" placeholder="用户名"/>
</el-col>
<el-col :span="5">
<el-select v-model="form.type" placeholder="选择类型">
<el-option label="管理员" value="1"/>
<el-option label="普通用户" value="2"/>
</el-select>
</el-col>
<el-col :span="2">
<el-button type="primary" @click="search" style="margin-right: 10px;">查询</el-button>
</el-col>
</el-form-item>
<el-form-item>
<el-tag type="success" @click="adduser({})" class="tag_hover">新增</el-tag>
<el-tag type="danger" @click="delete_user({})" class="tag_hover">删除</el-tag>
</el-form-item>
</el-form>
</div>
<div>
<el-table
v-loading="listLoading"
:data="list"
element-loading-text="Loading"
border
fit
highlight-current-row
@selection-change="handleSelectionChange"
>
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column align="center" label="id" width="95" prop="id" sortable>
</el-table-column>
<el-table-column label="用户名" align="center" prop="username">
</el-table-column>
<el-table-column label="邮箱" align="center" prop="email">
</el-table-column>
<el-table-column label="手机" align="center" prop="phone">
</el-table-column>
<el-table-column label="个人介绍" align="center" prop="introduce">
</el-table-column>
<el-table-column label="类型" align="center" prop="type">
<template v-slot="scope">
<el-tag :type="scope.row.type | statusFilter">{{ scope.row.type === 1 ? "管理员" : "普通用户" }}</el-tag>
</template>
</el-table-column>
<el-table-column label="创建时间" align="center" prop="create_time">
<template v-slot="scope">
<span>{{ scope.row.create_time.split("T")[0] }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center">
<template v-slot="scope">
<el-tag type="success" @click="adduser(scope.row)" class="tag_hover">修改</el-tag>
<el-tag type="danger" @click="delete_user(scope.row)" class="tag_hover">删除</el-tag>
</template>
</el-table-column>
</el-table>
<div class="block">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="1"
:page-sizes="[10, 20, 30, 40]"
:page-size="10"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</div>
<div>
<el-dialog :title="title" :visible.sync="show">
<Adduser :adduser_data="adduser_data"></Adduser>
<div slot="footer" class="dialog-footer">
<el-button @click="show = false">取 消</el-button>
<el-button type="primary" @click="submit">确 定</el-button>
</div>
</el-dialog>
</div>
</div>
</template>
<script>
import Adduser from "@/views/user/user_list/adduser"
export default {
components: {Adduser},
filters: {
statusFilter(status) {
const statusMap = {
1: 'success',
2: 'gray',
// deleted: 'danger'
}
return statusMap[status]
}
},
data() {
return {
list: null,
listLoading: true,
form: {
username: "",
type: ""
},
pageSize: 10,
currentPage: 1,
total: 0,
selectId: [],
adduser_data: {
username: "",
type: "",
phone: "",
email: "",
introduce: "",
password: "",
avatar:""
},
show: false,
title: "新增用户",
is_add: true,
id: ''
}
},
comments: {
Adduser
},
created() {
this.fetchData()
},
methods: {
fetchData() {
this.listLoading = true
this.axios.get("/api/users/list", {
params: {
username: this.form.username,
type: this.form.type,
pageSize: this.pageSize,
currentPage: this.currentPage
}
}).then(res => {
console.log(res.data)
this.list = res.data.data
this.total = res.data.total
this.listLoading = false
}).catch(err => {
console.log(err)
})
},
search() {
console.log(this.form)
this.fetchData()
},
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
console.log(`每页 ${val} 条`, val);
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
console.log(`当前页: ${val}`);
},
adduser(row) {
this.show = true
if (row.id) {
console.log(row.length)
this.adduser_data.username = row.username
this.adduser_data.type = row.type
this.adduser_data.phone = row.phone
this.adduser_data.email = row.email
this.adduser_data.introduce = row.introduce
this.adduser_data.password = row.password
this.adduser_data.avatar = row.avatar
this.id = row.id
this.is_add = false
}else{
this.adduser_data={
username: "",
type: "",
phone: "",
email: "",
introduce: "",
password: "",
avatar:""
}
}
},
submit() {
console.log(this.is_add)
if (this.is_add) {
this.axios.post("/api/users/register", {
username: this.adduser_data.username,
type: this.adduser_data.type,
phone: this.adduser_data.phone,
email: this.adduser_data.email,
introduce: this.adduser_data.introduce,
password: this.adduser_data.password,
avatar:this.adduser_data.avatar
}).then(res => {
if (res.data.code === 0) {
this.$message("添加成功")
} else {
this.$message("用户名已存在")
}
}).catch(err => {
console.log(err)
})
} else {
console.log(this.adduser_data)
this.axios.post("/api/users/update", {
id: this.id,
username: this.adduser_data.username,
type: this.adduser_data.type,
phone: this.adduser_data.phone,
email: this.adduser_data.email,
introduce: this.adduser_data.introduce,
password: this.adduser_data.password,
avatar:this.adduser_data.avatar
}).then(res => {
if (res.data.code === 0) {
this.$message("修改成功")
} else {
this.$message("用户名重复")
}
}).catch(err => {
console.log(err)
})
}
this.fetchData()
this.show = false
this.adduser_data = {
username: "",
type: "",
phone: "",
email: "",
introduce: "",
password: "",
}
},
delete_user(row) {
let ids = []
this.$confirm('是否删除?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
if (row.id) {
console.log(row)
ids.push(row.id)
} else if (this.selectId.length > 0) {
ids = this.selectId
} else {
this.$message("请选择用户")
}
this.axios.post("/api/users/delete", {"ids": ids}).then(res => {
this.$message("删除成功")
this.fetchData()
}).catch(err => {
console.log(err)
})
})
},
handleSelectionChange(val) {
this.selectId = []
val.forEach(e => {
this.selectId.push(e.id)
})
}
}
}
</script>
<style scoped>
</style>
|
package com.example.android_mvvm_with_room_database.db_utilities;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import com.example.android_mvvm_with_room_database.service.model.User;
import java.util.List;
@Dao
public interface UserDao {
@Insert
public void insert(User user);
@Query("SELECT * FROM users")
public LiveData<List<User>> getAllUsers();
@Delete
public void delete(User user);
@Update
public void update(User user);
}
|
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
JoinColumn,
ManyToOne,
} from 'typeorm';
import Category from './Category';
@Entity('transactions')
class Transaction {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('varchar')
title: string;
@Column('varchar')
type: 'income' | 'outcome';
@Column('int4')
value: number;
@Column('varchar')
category_id: string;
@ManyToOne(() => Category)
@JoinColumn({ name: 'category_id' })
category: Category;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
export default Transaction;
|
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Card from "../components/Card";
import { getData, getFilterData } from "../redux/action";
import styles from "../styles/User.module.css";
import { Input } from "@chakra-ui/react";
import { Button } from "@chakra-ui/react";
const Users = () => {
const [search, setSearch] = useState();
const [searchData, setSearchData] = useState();
const [filterCon, setFilterCon] = useState();
var compData = useSelector((state) => state.company);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getData());
}, []);
function handleSearch() {
console.log(search);
dispatch(getFilterData("company", search));
}
const handleChangeCon = (e) => {
console.log(e);
if(e == "pt"){
dispatch(getFilterData("contract","Part Time"))
}
if(e == "ft"){
dispatch(getFilterData("contract","Full Time"))
}
if(e == "fr"){
dispatch(getFilterData("contract","Freelance"))
}
}
// compData = searchData;
console.log(compData);
return (
<div>
<div className={styles.searchdiv}>
<Input
onChange={(e) => {
setSearch(e.target.value);
}}
placeholder="Search Company by Name"
size="md"
/>
<Button
className={styles.searchbtn}
colorScheme="teal"
size="sm"
onClick={handleSearch}
>
Search
</Button>
</div>
<div className={styles.filerDiv}>
<p className={styles.filterPara} >Filter by Contract</p>
<select onChange={(e) => handleChangeCon(e.target.value)} className={styles.contractSel}>
<option >None</option>
<option value="ft">Full-Time</option>
<option value="pt">Part-Time</option>
<option value="fr">Freelance</option>
</select>
</div>
<div className={styles.container}>
{compData?.map((e) => (
<div>
<Card {...e} />
</div>
))}
</div>
</div>
);
};
export default Users;
|
// testing custom hooks
// http://localhost:3000/counter-hook
import { expect, test } from 'vitest'
import { act, render, renderHook, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import useCounter from '@/hooks/use-counter'
function CounterConsumer() {
const { count, increment, decrement } = useCounter()
return (
<div>
<div data-testid="counter-text">Current count: {count}</div>
<button onClick={decrement}>Decrement</button>
<button onClick={increment}>Increment</button>
</div>
)
}
// let count, increment, decrement
// function CounterConsumer() {
// // 💰 here's how to use the hook:
// ;({count, increment, decrement} = useCounter())
// return null
// }
// function setup(props) {
// // let count, increment, decrement
// const result = {}
// function CounterConsumer() {
// // ;({count, increment, decrement} = useCounter(props))
// // result.current = useCounter(props) // NOTE, that the reference contained in the variable 'result' is not changed, but the contained property current is re-assigned
// Object.assign(result, useCounter(props)) // NOTE, that the reference contained in the variable 'result' is not changed, but its content properties are re-assigned
// return null
// }
// render(<CounterConsumer />)
// // return {count, increment, decrement}
// return result // NOTE, the whole point is that this thing shouldn't mutate when CounterConsumer is run
// }
test('exposes the count and increment/decrement functions', async () => {
render(<CounterConsumer />)
const message = screen.getByTestId('counter-text')
const decrement = screen.getByRole('button', { name: /decrement/i })
const increment = screen.getByRole('button', { name: /increment/i })
expect(message).toHaveTextContent('Current count: 0')
// expect(count).toBe(0)
await userEvent.click(increment)
// act(() => increment())
expect(message).toHaveTextContent('Current count: 1')
// expect(count).toBe(1)
await userEvent.click(decrement)
// act(() => decrement())
expect(message).toHaveTextContent('Current count: 0')
// expect(count).toBe(0)
})
test('allow customization of the initial count', async () => {
// const result = setup({initialCount: 42})
// const {result} = renderHook(() => useCounter({initialCount: 42}))
const { result } = renderHook(useCounter, {
initialProps: { initialCount: 42 },
})
render(<CounterConsumer />)
expect(result.current.count).toBe(42)
})
test('allow customization of the step', async () => {
// const {count, increment, decrement} = setup({step: 8}) // assigns the destructured value of count once
// const result = setup({step: 8}) // assigns to a wrapper variable around the reactive object, access with result.current.PROPERTY
// const result = setup({step: 8}) // assigns to a wrapper variable around the reactive object, access with result.PROPERTY
// const {result} = renderHook(() => useCounter({step: 8}))
const { result } = renderHook(useCounter, { initialProps: { step: 8 } })
// expect(result.count).toBe(0)
expect(result.current.count).toBe(0)
// act(() => result.increment())
act(() => result.current.increment())
// expect(result.count).toBe(8)
expect(result.current.count).toBe(8)
// act(() => result.decrement())
act(() => result.current.decrement())
// expect(result.count).toBe(0)
expect(result.current.count).toBe(0)
})
|
Creating Branded iOS and Android Apps (Enterprise Only)
Overview
--------
ownBrander is an ownCloud build service that is exclusive to Enterprise
customers, for easily creating your own branded Android and iOS
ownCloud sync apps, and your own branded ownCloud desktop sync client. Customers
will access the app through their `customer.owncloud.com
<https://customer.owncloud.com>`_ accounts.
.. image:: ../images/ownbrander-1.png
You need to supply your own artwork, and the wizard tells you the required
dimensions. To build Android and Desktop sync apps you need to supply only your
own custom branded artwork. Building any iOS app requires custom branded
artwork plus obtaining and installing a P12 certificate and provisioning
profile from Apple (see :ref:`creating-ios-apps`). Then, to create the app, you
follow a simple graphical wizard.
.. image:: ../images/ownbrander-2.png
When you have completed the wizard, you will either get messages warning you
of any items that need to be corrected, or a success message:
.. image:: ../images/ownbrander-3.png
And then when your new app is built, which may take up to 48 hours, it will
appear in your personal folder on the Files page.
.. image:: ../images/ownbrander-4.png
Creating Branded Android or Desktop Sync Clients
------------------------------------------------
You can play around with ownBrander and create some apps for testing and
learning. The Android and Desktop sync clients are the easiest to use for
testing, and we'll walk through creating an Android app. You need a just a few
images, and the wizard tells you their required dimensions. They must be the
exact specified dimensions, preferably in PNG format.
First, start on the Common tab and enter your application name and the URL to
your ownCloud server. For testing purposes these can be anything. These are
your global defaults, and you can change them when you create your apps. When
you create production apps, then you must use your real app name, and the URL
must point to your real ownCloud server.
.. image:: ../images/ownbrander-5.png
Now go to the Android tab. There is a lot of helpful information on this page.
Fill in your Application name, or keep the default set from the Common tab,
and the Android package name.
.. image:: ../images/ownbrander-6.png
Next, upload your images. The wizard tells you the exact size they must be, and
click the images on the right to see some example screenshots.
.. image:: ../images/ownbrander-7.png
Next, you have the option to display a New Account link on users' login
screens. This is a simple mechanism for users to create new accounts. Then you
can have a default root folder name that displays at the top of users' screens,
such as home, your company name, or anything you want.
.. image:: ../images/ownbrander-8.png
The next option is enabling a help URL. This can be a link to documentation on
your own site, or to `doc.owncloud.org <https://doc.owncloud.org>`_. Then you
have options to enable a "Recommend" feature so your users can recommend your
app to other users, and a feedback option so they can tell you what they think
of your app.
.. image:: ../images/ownbrander-9.png
The Imprint URL option allows you to enter a link to information about your
company. The URL to download the app is automatically generated by ownBrander,
or you may enter an alternate download link.
.. image:: ../images/ownbrander-10.png
Finally, if you are creating a paid app then check the checkbox for Paid Users
and upload an icon.
.. image:: ../images/ownbrander-11.png
Now you are finished. Click the Generate Android App button, and you will
either see a success message, or an error message telling you what you need to
fix. When all of your options are entered correctly and you click the Generate
Android App button, it takes up to 48 hours for your app to appear on your
Files page.
.. image:: ../images/ownbrander-12.png
.. _creating-ios-apps:
Creating Apps for iOS
---------------------
You need many more images for creating an iOS app so that your app works on all
iPhones and iPads in both portrait and landscape modes. You also need an Apple
developer account, and a `P12 certificate and provisioning profile
<https://developer.apple.com/library/ios/documentation/Security/Conceptual/
CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html#//apple_ref/doc/uid/
TP40001358-CH208-SW13>`_. We will install these for you on your
`customer.owncloud.com
<https://customer.owncloud.com>`_ account. Contact [email protected] if you
have any questions.
|
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "pch.h"
#include "IDatasmithSceneElements.h"
#include "Templates/SharedPointer.h"
const FString& GetExportPath();
void SetExportPath(const FString& Path);
/**
* For this sample application, some parameters are shared by all the scene. To avoid repetition, this is setup there.
*/
void SetupSharedSceneProperties(TSharedRef<IDatasmithScene> DatasmithScene);
struct ISampleScene
{
// a simple name to identify that scene
virtual FString GetName() const = 0;
// a longer, optionnal description
virtual FString GetDescription() const { return {}; }
// list the themes used in this scene (eg. Instancing, LOD, Collision, etc.)
virtual TArray<FString> GetTags() const { return {}; }
// export a udatasmith scene
virtual TSharedPtr<IDatasmithScene> Export() { return nullptr; }
};
#define REGISTER_SCENE(Type) \
static struct AutoRegister ## Type {\
AutoRegister ## Type() { FScenesManager::Register(MakeShared<Type>()); }\
} AutoRegisterInstance ## Type;
class FScenesManager
{
public:
// Register a new scene. Prefer the REGISTER_SCENE macro
static void Register(TSharedPtr<ISampleScene> SampleScene);
static const TArray<TSharedPtr<ISampleScene>>& GetAllScenes();
static TSharedPtr<ISampleScene> GetScene(const FString& Name);
};
|
from django.contrib.auth import authenticate
from django.utils.translation import gettext_lazy as _
from django.conf import settings
from django.core.validators import validate_email
from rest_framework import serializers
from users.models import *
import datetime
class SignupSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
password = serializers.CharField(required=True)
name = serializers.CharField(required=True)
def validate_email(self, email):
is_valid_email = False
try:
validate_email(email)
except Exception as excepted_message:
raise Exception('Please use valid email for registration.')
if User.objects.filter(email__iexact=email).exists():
raise Exception('This user already exists. Please sign in.')
return str(email).strip().lower()
def save(self):
name = self.validated_data['name']
email = self.validated_data['email']
password = self.validated_data['password']
user = User.objects.create(name=name, email=email)
user.is_active = True
user.set_password(password)
user.save()
return user
class AuthenticationSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
email = attrs['email']
password = attrs['password']
if email and password:
user = authenticate(request=self.context['request'], email=str(email).strip().lower(), password=password)
print(user)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
if not user.is_active:
msg = _('User is set Not Active')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "username" and "password".')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
class UserProductsSerializer(serializers.ModelSerializer):
title = serializers.SerializerMethodField()
visited_at = serializers.SerializerMethodField()
class Meta:
model = UserProducts
fields = ['id', 'title', 'is_favourite', 'is_item_in_cart', 'view_count', 'is_brought', 'visited_at']
def get_title(self, instance):
return instance.product.title
def get_visited_at(self, instance):
return instance.updated_at.strftime("%d %b %Y")
class UserOrderHistorySerializer(serializers.ModelSerializer):
title = serializers.SerializerMethodField()
order_date = serializers.SerializerMethodField()
class Meta:
model = UserOrderHistory
fields = ['id', 'title', 'price', 'quantity', 'order_date']
def get_title(self, instance):
return instance.product.title
def get_order_date(self, instance):
return instance.order_date.strftime("%d %b %Y")
class UserProfileSerializer(serializers.ModelSerializer):
history = serializers.SerializerMethodField()
order_history = serializers.SerializerMethodField()
class Meta:
model = User
fields = ['id', 'name', 'email', "history", "order_history"]
def get_history(self, instance):
return_dict = []
products = instance.products.all().order_by("-updated_at")
for each_product in products:
each_dict = {"id":each_product.id, "title":each_product.product.title, "view_count":each_product.view_count}
each_dict["visited_at"] = each_product.updated_at.strftime("%d %b %Y")
return_dict.append(each_dict)
return return_dict
def get_order_history(self, instance):
return_dict = []
products = instance.orders.all().order_by("-order_date")
for each_product in products:
each_dict = {"id":each_product.id, "title":each_product.product.title, "price":each_product.product.price, "quantity":each_product.quantity}
each_dict["order_date"] = each_product.order_date.strftime("%d %b %Y")
return_dict.append(each_dict)
return return_dict
|
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
function AddAirport() {
const navigate = useNavigate();
const [country, setCountry] = useState('');
const [city, setCity] = useState('');
const [airport, setAirport] = useState('');
const [authToken, setAuthToken] = useState('');
useEffect(() => {
const authTokenData = localStorage.getItem('authToken');
if (!authTokenData) {
navigate('/login');
return;
}
const { authToken: token, expirationTime } = JSON.parse(authTokenData);
if (new Date().getTime() > expirationTime) {
localStorage.removeItem('authToken');
navigate('/login');
return;
}
setAuthToken(token); // Iestatiet authToken vērtību
}, [navigate]);
const handleCountryChange = event => {
setCountry(event.target.value);
};
const handleCityChange = event => {
setCity(event.target.value);
};
const handleAirportChange = event => {
setAirport(event.target.value);
};
const addAirport = async () => {
try {
const response = await fetch('http://localhost:8080/admin/addAirport', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${authToken}`,
},
body: JSON.stringify({ country, city, airport }),
});
if (response.ok) {
console.log('Airport added successfully');
window.alert('Airport added successfully');
setCountry('');
setCity('');
setAirport('');
navigate('/adminAirport');
} else {
console.error('ERROR: adding airport');
window.alert('ERROR adding airport');
}
} catch (error) {
console.error('ERROR adding airport', error);
window.alert('ERROR adding airport');
}
};
return (
<div className="d-flex justify-content-center align-items-center" style={{ height: '100vh' }}>
<form className="text-center ">
<h2>Add Airport</h2>
<div className="mb-3">
<label className="form-label">Country:</label>
<input type="text" className="form-control" value={country} onChange={handleCountryChange} />
</div>
<div className="mb-3">
<label className="form-label">City:</label>
<input type="text" className="form-control" value={city} onChange={handleCityChange} />
</div>
<div className="mb-3">
<label className="form-label">Airport:</label>
<input type="text" className="form-control" value={airport} onChange={handleAirportChange} />
</div>
<button type="button" className="btn btn-primary" onClick={addAirport}>Add Airport</button>
</form>
</div>
);
}
export default AddAirport;
|
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait HasImageCompetitionTeam
{
/**
* Update the user's CV.
*
* @param string $storagePath
* @return void
*/
public function updateImageCompetitionTeam(UploadedFile $image, $storagePath = 'competition-team-images')
{
tap($this->image_path, function ($previous) use ($image, $storagePath) {
if ($previous) {
Storage::disk($this->ImageCompetitionTeamDisk())->delete($previous);
}
$this->forceFill([
'image_path' => $image->storePublicly(
$storagePath, ['disk' => $this->ImageCompetitionTeamDisk()]
),
])->save();
});
}
/**
* Delete the user's CV.
*
* @return void
*/
public function deleteImageSlot()
{
if (is_null($this->image_path)) {
return;
}
Storage::disk($this->ImageCompetitionTeamDisk())->delete($this->image_path);
$this->forceFill([
'image_path' => null,
])->save();
}
/**
* Get the URL to the user's CV.
*/
public function ImageCompetitionTeamUrl(): Attribute
{
return Attribute::get(fn () => $this->image_path ? Storage::disk($this->ImageCompetitionTeamDisk())->url($this->image_path) : null); // TODO: should add default image
}
/**
* Get the disk that CVs should be stored on.
*
* @return string
*/
protected function ImageCompetitionTeamDisk()
{
return config('jetstream.competition_team_image_disk', 'public');
}
}
|
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast",
"sap/ui/core/Fragment"
], function (
Controller,
MessageToast,
Fragment,
) {
"use strict";
return Controller.extend("<id>.controller.HelloPanel", {
OnShowHello: function () {
//read message from i18n model
var oBundle = this.getView().getModel("i18n").getResourceBundle(); //获取i18n的资源绑定
var sRecipient = this.getView().getModel().getProperty("/recipient/name"); //过去oModel模型的recipient/name属性
var sMsg = oBundle.getText("helloMsg", [sRecipient]); //i18n文件的helloMsg=Hello 拼接/recipient/name 的UI5 = Hello UI5
// alert("Hello there!");
MessageToast.show(sMsg);
},
// onOpenDialog:function(){
// var oView = this.getView(); //onDialog按钮在HelloPanel.view视图,因此oView是HelloPanel.view视图对象
// if(!this.byId("helloDialog")){ //如果找不到helloDialog,就创建
// Fragment.load({
// id:oView.getId(),
// name:"sap.u.demo.walkthrough.view.HelloDialog"
// }).then(function(oDialog){ //创建了Dialog对象oDialog
// //将oDialog添加到HelloPanel.view视图对象oView
// oView.addDependent(oDialog);
// oDialog.open();
// })
// }else{
// //如果找得到helloDialog,直接打开
// this.byId("helloDialog").open();
// }
// }
// onOpenDialog: function () {
// var oView = this.getView();
// // create the dialog lazily
// if (!this.byId("helloDialog")) {
// // load asynchronous XML fragment
// Fragment.load({
// id: oView.getId(),
// name: "sap.ui.demo.walkthrough.view.HelloDialog",
// Controller:this
// }).then(function (oDialog) {
// // connect dialog to the root view of this component (models, lifecycle)
// oView.addDependent(oDialog);
// oDialog.open();
// })
// } else {
// this.byId("helloDialog").open();
// }
// }
onOpenDialog: function () {
// create dialog lazily
// if (!this.pDialog) {
// this.pDialog = this.loadFragment({
// name: "sap.ui.demo.walkthrough.view.HelloDialog",
// Controller:this
// });
// }
// this.pDialog.then(function (oDialog) {
// oDialog.open();
// });
// }
// create dialog lazily
this.getOwnerComponent().openHelloDialog();
},
onCloseDialog: function () {
this.byId("helloDialog").close();
}
});
});
|
import 'hello_angular/polyfills';
import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Http, HttpModule } from '@angular/http';
const RESULTS = [
{
first_name: "Pat",
last_name: "Smith",
username: "psmith",
email: "[email protected]",
created_at: "2016-02-05",
},
{
first_name: "Patrick",
last_name: "Jones",
username: "pjpj",
email: "[email protected]",
created_at: "2014-03-05",
},
{
first_name: "Patricia",
last_name: "Benjamin",
username: "pattyb",
email: "[email protected]",
created_at: "2016-01-02",
},
{
first_name: "Patty",
last_name: "Patrickson",
username: "ppat",
email: "[email protected]",
created_at: "2016-02-05",
},
{
first_name: "Jane",
last_name: "Patrick",
username: "janesays",
email: "[email protected]",
created_at: "2013-01-05",
},
];
let CustomerSearchComponent = Component({
selector: 'shine-customer-search',
template: `
<header>
<h1 class="h2">Customer Search</h1>
</header>
<section class="search-form">
<form>
<label for="keywords" class="sr-only">Keywords</label>
<input type="text" id="keywords" name="keywords"
placeholder="First Name, Last Name, or Email Address"
class="form-control input-lg"
bind-ngModel="keywords"
on-ngModelChange="search($event)"/>
</form>
</section>
<section class="search-results">
<header>
<h1 class="h3">Results</h1>
</header>
<ol class="list-group">
<ng-template ngFor bind-ngForOf="customers" let-customer>
<li class="list-group-item clearfix">
<h3 class="pull-right">
<small class="text-uppercase">Joined</small>
{{customer.created_at}}
</h3>
<h2 class="h3">
{{customer.first_name}} {{customer.last_name}}
<small>{{customer.username}}</small>
</h2>
<h4>{{customer.email}}</h4>
</li>
</ng-template>
</ol>
</section>`,
}).Class({
constructor: [
Http,
function(http) {
this.customers = null;
this.http = http;
this.keywords = '';
}
],
search($event) {
this.keywords = $event;
if (this.keywords.length < 3) {
return;
}
this.http.get(
'/customers.json?keywords=' + this.keywords
).subscribe(
(response) => {
this.customers = response.json().customers;
},
(response) => {
window.alert(response);
}
);
},
});
let CustomerAppModule = NgModule({
imports: [BrowserModule, FormsModule, HttpModule],
declarations: [CustomerSearchComponent],
bootstrap: [CustomerSearchComponent],
})
.Class({
constructor() {
},
});
platformBrowserDynamic().bootstrapModule(CustomerAppModule);
|
package hello.core;
import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.MemberRepository;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
// 애플리케이션 실제 동작에 필요한 구현 객체를 생성한다
// 생성한 객체 인스턴스의 참조를 생성자를 통해 주입(연결)한다.
// --> impl은 구체 클래스 몰라도 됨
// => DI (의존관계 주입)
@Bean
public MemberService memberService(){
System.out.println("AppConfig.memberService");
return new MemberServiceImpl(memberRepository());
}
// bean : spring container에 등록
@Bean
public MemberRepository memberRepository() {
System.out.println("AppConfig.memberRepository");
return new MemoryMemberRepository();
}
@Bean
public OrderService orderService() {
System.out.println("AppConfig.orderService");
return new OrderServiceImpl((MemoryMemberRepository) memberRepository(),discountPolicy());
// return null;
}
@Bean
public DiscountPolicy discountPolicy() {
return new RateDiscountPolicy();
}
}
|
@isTest
private class RuleExpression_Test
{
static testmethod void EvalTrue_Test()
{
//ns__Job__c!=null && ns__Tracking_Number__c!=null
//&& (ns__SyncID__c == 'syncId1' || ns__SyncID__c == 'syncId2' || ns__SyncID__c == 'syncId3')
String syncId1 = StringUtility.newGuid();
String syncId2 = StringUtility.newGuid();
String syncId3 = StringUtility.newGuid();
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"!=\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Job__c\\"},\\"right\\":{\\"type\\":\\"Constant\\",\\"value\\":\\"null\\"}}","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"!=\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Tracking_Number__c\\"},\\"right\\":{\\"type\\":\\"Constant\\",\\"value\\":\\"null\\"}}","&&","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__SyncID__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'syncId1\'\\"}}","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__SyncID__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'syncId2\'\\"}}","||","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__SyncID__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'syncId3\'\\"}}","||","&&"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace()).replace('syncId1', syncId1).replace('syncId2', syncId2).replace('syncId3', syncId3);
System.debug(ruleStack);
Ticket__c tkt = AlpineTestHelper.CreateTickets(1, false).get(0);
tkt.SyncID__c = syncId3;
insert tkt;
Ticket__c dbTkt = [SELECT Id, Tracking_Number__c, SyncID__c, Job__c FROM Ticket__c WHERE Id=:tkt.Id];
Boolean r = RuleExpression.Eval(ruleStack, dbTkt);
System.assert(r==true, 'true && true && (false || false || true) should eval to true');
}
static testmethod void EvalFalse_Test()
{
//ns__Job__c!=null && ns__Tracking_Number__c!=null
//&& (ns__SyncID__c == 'syncId1' || ns__SyncID__c == 'syncId2' || ns__SyncID__c == 'syncId3')
String syncId1 = StringUtility.newGuid();
String syncId2 = StringUtility.newGuid();
String syncId3 = StringUtility.newGuid();
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"!=\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Job__c\\"},\\"right\\":{\\"type\\":\\"Constant\\",\\"value\\":\\"null\\"}}","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"!=\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Tracking_Number__c\\"},\\"right\\":{\\"type\\":\\"Constant\\",\\"value\\":\\"null\\"}}","&&","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__SyncID__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'syncId1\'\\"}}","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__SyncID__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'syncId2\'\\"}}","||","{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__SyncID__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'syncId3\'\\"}}","||","&&"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace()).replace('syncId1', syncId1).replace('syncId2', syncId2).replace('syncId3', syncId3);
Ticket__c tkt = AlpineTestHelper.CreateTickets(1, false).get(0);
tkt.SyncID__c = StringUtility.newGuid();
insert tkt;
Ticket__c dbTkt = [SELECT Id, Tracking_Number__c, SyncID__c, Job__c FROM Ticket__c WHERE Id=:tkt.Id];
Boolean r = RuleExpression.Eval(ruleStack, dbTkt);
System.assert(r==false, 'true && true && (false || false || false) should eval to false');
}
static testmethod void EvalDatetimeTrue_Test()
{
//ns__Work_Start_Date__c>'2017-03-17T11:00:00.000Z'
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\">\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Work_Start_Date__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'2017-03-17T11:00:00.000Z\'\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket__c obj = new Ticket__c();
obj.Work_Start_Date__c = Datetime.now();
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==true, 'Datetime comparison true');
}
static testmethod void EvalDatetimeFalse_Test()
{
//ns__Work_Start_Date__c>'2017-03-17T11:00:00.000Z'
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\">\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Work_Start_Date__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'2017-03-17T11:00:00.000Z\'\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket__c obj = new Ticket__c();
obj.Work_Start_Date__c = Datetime.valueOfGmt('2017-03-17 11:00:00.000Z').addDays(-10);
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==false, 'Datetime comparison false');
}
static testmethod void EvalBooleanTrue_Test()
{
//rule ns__Sync__c == true
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Sync__c\\"},\\"right\\":{\\"type\\":\\"Constant\\",\\"value\\":\\"true\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket__c obj = new Ticket__c();
obj.Sync__c = true;
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==true, 'Boolean comparison true');
}
static testmethod void EvalBooleanFalse_Test()
{
//rule ns__Sync__c == true
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\"==\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Sync__c\\"},\\"right\\":{\\"type\\":\\"Constant\\",\\"value\\":\\"true\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket__c obj = new Ticket__c();
obj.Sync__c = false;
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==false, 'Boolean comparison false');
}
static testmethod void EvalDateFalse_Test()
{
//rule ns__Ticket_Date__c > '2017-03-17'
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\">\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Ticket_Date__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'2017-03-17\'\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket__c obj = new Ticket__c();
obj.Ticket_Date__c = Date.valueOf('2017-03-17').addDays(-10);
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==false, 'Date comparison false');
}
static testmethod void EvalDateTrue_Test()
{
//rule ns__Ticket_Date__c > '2017-03-17'
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\">\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Ticket_Date__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":\\"\'2017-03-17\'\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket__c obj = new Ticket__c();
obj.Ticket_Date__c = Date.valueOf('2017-03-17').addDays(20);
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==true, 'Date comparison true');
}
static testmethod void EvalCurrencyFalse_Test()
{
//rule criteria Price__c>100
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\">\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Price__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":100}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket_Item__c obj = new Ticket_Item__c();
obj.Price__c = 50;
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==false, 'Currency comparison false');
}
static testmethod void EvalCurrencyTrue_Test()
{
//rule criteria Price__c>100
String ruleStack = '["{\\"type\\":\\"BinaryExpression\\",\\"operator\\":\\">\\",\\"left\\":{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Price__c\\"},\\"right\\":{\\"type\\":\\"Literal\\",\\"value\\":100}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Ticket_Item__c obj= new Ticket_Item__c();
obj.Price__c = 200;
Boolean r = RuleExpression.Eval(ruleStack, obj);
System.assert(r==true, 'Currency comparison true');
}
static testmethod void EvalIncludes_True_Test()
{
//rule criteria: includes(Applied_To__c, 'Ticket__c')
String ruleStack = '["{\\"type\\":\\"CallExpression\\",\\"args\\":[{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Applies_To__c\\"},{\\"type\\":\\"Literal\\",\\"value\\":\\"\'Ticket__c\'\\"}],\\"callee\\":{\\"type\\":\\"Identifier\\",\\"name\\":\\"includes\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Price_Book_Rule__c r = new Price_Book_Rule__c();
r.Applies_To__c = 'Ticket__c;Quote__c';
Boolean result = RuleExpression.Eval(ruleStack, r);
System.assert(result==true, 'MuiltiSelect picklist true');
}
static testmethod void EvalIncludes_false_Test()
{
//rule criteria: includes(Applied_To__c, 'Ticket__c')
String ruleStack = '["{\\"type\\":\\"CallExpression\\",\\"args\\":[{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Applies_To__c\\"},{\\"type\\":\\"Literal\\",\\"value\\":\\"\'Ticket__c\'\\"}],\\"callee\\":{\\"type\\":\\"Identifier\\",\\"name\\":\\"includes\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Price_Book_Rule__c r = new Price_Book_Rule__c();
r.Applies_To__c = 'Quote__c';
Boolean result = RuleExpression.Eval(ruleStack, r);
System.assert(result==false, 'MuiltiSelect picklist false');
}
static testmethod void EvalExcludes_true_Test()
{
//rule criteria: excludes(Applied_To__c, 'Ticket__c')
String ruleStack = '["{\\"type\\":\\"CallExpression\\",\\"args\\":[{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Applies_To__c\\"},{\\"type\\":\\"Literal\\",\\"value\\":\\"\'Ticket__c\'\\"}],\\"callee\\":{\\"type\\":\\"Identifier\\",\\"name\\":\\"excludes\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Price_Book_Rule__c r = new Price_Book_Rule__c();
r.Applies_To__c = 'Quote__c';
Boolean result = RuleExpression.Eval(ruleStack, r);
System.assert(result==true, 'MuiltiSelect picklist excludes true');
}
static testmethod void EvalExcludes_false_Test()
{
//rule criteria: excludes(Applied_To__c, 'Ticket__c')
String ruleStack = '["{\\"type\\":\\"CallExpression\\",\\"args\\":[{\\"type\\":\\"Identifier\\",\\"value\\":\\"ns__Applies_To__c\\"},{\\"type\\":\\"Literal\\",\\"value\\":\\"\'Ticket__c\'\\"}],\\"callee\\":{\\"type\\":\\"Identifier\\",\\"name\\":\\"excludes\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Price_Book_Rule__c r = new Price_Book_Rule__c();
r.Applies_To__c = 'Ticket__c;Quote__c';
Boolean result = RuleExpression.Eval(ruleStack, r);
System.assert(result==false, 'MuiltiSelect picklist excludes false');
}
static testmethod void EvalContains_true_Test()
{
//rule criteria: excludes(Job__r.Name, 'LFW Test Job')
String ruleStack = '["{\\"type\\":\\"CallExpression\\",\\"args\\":[{\\"type\\":\\"MemberExpression\\",\\"value\\":\\"ns__Job__r.Name\\"},{\\"type\\":\\"Literal\\",\\"value\\":\\"\'LFW Test Job\'\\"}],\\"callee\\":{\\"type\\":\\"Identifier\\",\\"name\\":\\"contains\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Job__c j = AlpineTestHelper.CreateJobs(1, false).get(0);
j.Name = 'LFW Test Job' + StringUtility.newGuid();
Ticket__c tkt = AlpineTestHelper.CreateTickets(1, false).get(0);
tkt.Job__r = j;
Boolean result = RuleExpression.Eval(ruleStack, tkt);
System.assert(result==true, 'Contains string true');
}
static testmethod void EvalContains_false_Test()
{
//rule criteria: excludes(Job__r.Name, 'LFW Test Job')
String ruleStack = '["{\\"type\\":\\"CallExpression\\",\\"args\\":[{\\"type\\":\\"MemberExpression\\",\\"value\\":\\"ns__Job__r.Name\\"},{\\"type\\":\\"Literal\\",\\"value\\":\\"\'LFW Test Job\'\\"}],\\"callee\\":{\\"type\\":\\"Identifier\\",\\"name\\":\\"contains\\"}}"]';
ruleStack = ruleStack.replace('ns__', StringUtility.FXNamespace());
Job__c j = AlpineTestHelper.CreateJobs(1, false).get(0);
j.Name = 'Job' + StringUtility.newGuid();
Ticket__c tkt = AlpineTestHelper.CreateTickets(1, false).get(0);
tkt.Job__r = j;
Boolean result = RuleExpression.Eval(ruleStack, tkt);
System.assert(result==false, 'Contains string false');
}
}
|
import { InMemoryAdministratorsRepository } from 'test/repositories/in-memory-administrators-repository'
import { LoginAdministratorUseCase } from './login-administrator'
import { makeAdministrator } from 'test/factories/make-administrator'
import { CredentialsDoNotMatch } from '@/core/errors/errors/credentials-do-not-match'
let inMemoryAdministratorsRepository: InMemoryAdministratorsRepository
let sut: LoginAdministratorUseCase
describe('Login Administrator', () => {
beforeEach(() => {
inMemoryAdministratorsRepository = new InMemoryAdministratorsRepository()
sut = new LoginAdministratorUseCase(inMemoryAdministratorsRepository)
})
it('should be able to do login on application', async () => {
const newAdministrator = makeAdministrator({
name: 'John Doe',
})
inMemoryAdministratorsRepository.items.push(newAdministrator)
const result = await sut.execute({
cpf: newAdministrator.cpf,
password: newAdministrator.password,
})
expect(result.isRight()).toBe(true)
expect(result.value).toMatchObject({
administrator: { name: 'John Doe', cpf: newAdministrator.cpf },
})
})
it('should not be able to do login on application with invalid cpf', async () => {
const newAdministrator = makeAdministrator({
name: 'John Doe',
})
inMemoryAdministratorsRepository.items.push(newAdministrator)
const result = await sut.execute({
cpf: 'Invalid cpf',
password: newAdministrator.password,
})
expect(result.isLeft()).toBe(true)
expect(result.value).toBeInstanceOf(CredentialsDoNotMatch)
})
it('should not be able to do login on application with invalid password', async () => {
const newAdministrator = makeAdministrator({
name: 'John Doe',
password: '123456',
})
inMemoryAdministratorsRepository.items.push(newAdministrator)
const result = await sut.execute({
cpf: newAdministrator.cpf,
password: 'Invalid password',
})
expect(result.isLeft()).toBe(true)
expect(result.value).toBeInstanceOf(CredentialsDoNotMatch)
})
})
|
;;; loophole-tests.el --- Tests for Loophole -*- lexical-binding: t -*-
;; Copyright (C) 2022 0x60DF
;; Author: 0x60DF <[email protected]>
;; URL: https://github.com/0x60df/loophole
;; Package-Requires: ((emacs "27.1") (loophole "0.8.3"))
;; This file is not part of GNU Emacs.
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Loophole-tests provides the tests for Loophole.
;; Load this library and call `ert' to run the tests.
;;; Code:
(require 'loophole)
(require 'ert)
(require 'seq)
;; Test tools
(defvar loophole--test-barriered-symbol-list nil
"List of symbols which is barriered in testing environment.
In `loophole--test-with-pseudo-environment', `intern' and
`unintern' applied to the symbols listed in this variable
or the symbols prefixed by loophole are deflected to
temporary `obarray'.
Note that, if obarray is specified explicitly for
`intern' and `unintern', deflection does not performed.")
(defconst loophole--test-wait-time 0.5
"Time to signal `loophole-test-error' for tests that reads events.")
(define-error 'loohpole-test-error "Loophole test error" 'error)
(defmacro loophole--test-with-pseudo-environment (&rest body)
"Evaluate BODY with pseudo environment for Loophole.
In this macro, temporary buffer is set as current by
`with-temp-buffer'.
All the global Loophole variables and
`emulation-mode-map-alists' are let-bound to isolate them
from ordinary environment and prevent side effect.
Local Loophole variables are saved and killed. Saved values
are restored by `unwind-protect'.
`intern' and `unintern' are advised to use temporary obarray
instead of standard `obarray' if specified symbol has prefix
loophole, or is a member of
`loophole--test-barriered-symbol-list'.
Advice are removed after evaluating BODY by `unwind-protet'.
The symbol interned to temporary obarray is isolated from
oridinary environment, and barriered from side effect.
Variable watcher and hook functions added by `loophole-mode'
are temporarily removed to prevenet side effect.
Symbols which are manipulated by the form being tested
should be referred via `intern'.
Most variables are set as initial value. User options for
automation whose default value is t are set as nil.
`emulation-mode-map-alists' is set as a list containing
only `loophole--map-alist'.
Default value of local variables are set as initial value."
(declare (debug t) (indent 0))
(let ((temp-obarray (make-symbol "temp-obarray"))
(mode-state (make-symbol "mode-state"))
(local-variable-if-set-list (make-symbol "local-variable-if-set-list"))
(local-variable-alist (make-symbol "local-variable-alist")))
`(let ((loophole--buffer-list t)
(loophole--suspended nil)
(loophole-base-map (make-sparse-keymap))
(loophole-temporary-map-max 8)
(loophole-allow-keyboard-quit t)
(loophole-decide-obtaining-method-after-read-key
'negative-argument)
(loophole-protect-keymap-entry t)
(loophole-read-key-limit-time 1.0)
(loophole-read-key-termination-key (where-is-internal
'keyboard-quit nil t))
(loophole-read-buffer-inhibit-recursive-edit nil)
(loophole-read-buffer-finish-key [?\C-c ?\C-c])
(loophole-read-buffer-abort-key [?\C-c ?\C-k])
(loophole-force-overwrite-bound-variable t)
(loophole-force-make-variable-buffer-local t)
(loophole-force-unintern nil)
(loophole-make-register-always-read-tag 'infer)
(loophole-make-describe-use-builtin nil)
(loophole-timer-default-time (* 60 60))
(loophole-editing-timer-default-time (* 60 5))
(loophole-command-by-lambda-form-format
(concat "(lambda (&optional arg)\n"
" \"Temporary command on `loophole'.\"\n"
" (interactive \"P\")\n"
" (#))"))
(loophole-defining-kmacro-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c[" #'loophole-end-kmacro)
(define-key map "\C-c\\" #'loophole-abort-kmacro)
map))
(loophole-defining-kmacro-map-flag t)
(loophole-defining-kmacro-map-tag
(concat "kmacro[End: \\[loophole-end-kmacro], "
"Abort: \\[loophole-abort-kmacro]]"))
(loophole-alternative-read-key-function
#'loophole-read-key-with-time-limit)
(loophole-bind-entry-order
'(loophole-obtain-object))
(loophole-bind-command-order
'(loophole-obtain-command-by-read-command
loophole-obtain-command-by-key-sequence
loophole-obtain-command-by-lambda-form
loophole-obtain-object))
(loophole-bind-kmacro-order
'(loophole-obtain-kmacro-by-recursive-edit
loophole-obtain-kmacro-by-read-key
loophole-obtain-kmacro-by-recall-record
loophole-obtain-object))
(loophole-bind-array-order
'(loophole-obtain-array-by-read-key
loophole-obtain-array-by-read-string
loophole-obtain-object))
(loophole-bind-keymap-order
'(loophole-obtain-keymap-by-read-keymap-variable
loophole-obtain-keymap-by-read-keymap-function
loophole-obtain-object))
(loophole-bind-symbol-order
'(loophole-obtain-symbol-by-read-keymap-function
loophole-obtain-symbol-by-read-command
loophole-obtain-symbol-by-read-array-function
loophole-obtain-object))
(loophole-set-key-order
'(loophole-obtain-command-by-read-command
loophole-obtain-kmacro-by-recursive-edit
loophole-obtain-command-by-key-sequence
loophole-obtain-kmacro-by-read-key
loophole-obtain-command-by-lambda-form
loophole-obtain-kmacro-by-recall-record
loophole-obtain-object))
(loophole-after-register-functions nil)
(loophole-after-unregister-functions nil)
(loophole-after-prioritize-functions nil)
(loophole-after-globalize-functions nil)
(loophole-after-localize-functions nil)
(loophole-after-enable-functions nil)
(loophole-after-disable-functions nil)
(loophole-after-start-editing-functions nil)
(loophole-after-stop-editing-functions nil)
(loophole-after-globalize-editing-functions nil)
(loophole-after-localize-editing-functions nil)
(loophole-after-name-functions nil)
(loophole-after-merge-functions nil)
(loophole-after-duplicate-functions nil)
(loophole-read-buffer-set-up-hook nil)
(loophole-bind-hook nil)
(loophole-default-storage-file
(concat user-emacs-directory "loophole-maps"))
(loophole-make-load-overwrite-map 'temporary)
(loophole-print-event-in-char-read-syntax t)
(loophole-tag-sign "#")
(loophole-mode-lighter-base " L")
(loophole-mode-lighter-editing-sign "+")
(loophole-mode-lighter-suspending-sign "-")
(loophole-mode-lighter-preset-alist
'((tag . (""
loophole-mode-lighter-base
(:eval (if (and (loophole-suspending-p)
(not loophole-mode-lighter-use-face))
loophole-mode-lighter-suspending-sign))
(:eval (if (loophole-editing)
(concat
loophole-mode-lighter-editing-sign
(let ((tag (get (loophole-editing)
:loophole-tag)))
(if (and loophole-mode-lighter-use-face
(stringp tag))
(propertize (replace-regexp-in-string
"%" "%%"
(substitute-command-keys
tag))
'face 'loophole-editing)
tag)))))
(:eval
(let ((l (seq-filter #'symbol-value
(loophole-state-variable-list))))
(if (zerop (length l))
""
(concat
loophole-tag-sign
(mapconcat
(lambda (state-variable)
(let ((e (replace-regexp-in-string
"%" "%%"
(substitute-command-keys
(let ((tag (get
(get
state-variable
:loophole-map-variable)
:loophole-tag)))
(if (stringp tag)
tag
""))))))
(if (and loophole-mode-lighter-use-face
(stringp e))
(propertize e
'face
(if (loophole-suspending-p)
'loophole-suspending
'loophole-using))
e)))
l ",")))))))
(number . (""
loophole-mode-lighter-base
(:eval (if (and (loophole-suspending-p)
(not loophole-mode-lighter-use-face))
loophole-mode-lighter-suspending-sign))
(:eval (if (loophole-editing)
loophole-mode-lighter-editing-sign))
(:eval (let ((n (length
(seq-filter
#'symbol-value
(loophole-state-variable-list)))))
(if (zerop n)
""
(concat
":"
(let ((s (int-to-string n)))
(if loophole-mode-lighter-use-face
(propertize
s 'face
(if (loophole-suspending-p)
'loophole-suspending
'loophole-using))
s))))))))
(simple . (""
loophole-mode-lighter-base
(:eval (if (loophole-suspending-p)
loophole-mode-lighter-suspending-sign))
(:eval (if (loophole-editing)
loophole-mode-lighter-editing-sign))))
(static . loophole-mode-lighter-base)))
(loophole-mode-lighter-use-face nil)
(loophole-auto-start-editing-for-existing-binding-advice nil)
(loophole-idle-prioritize-timer nil)
(loophole-idle-save-timer nil)
(loophole-use-auto-prioritize nil)
(loophole-use-auto-stop-editing nil)
(loophole-use-auto-resume nil)
(loophole-use-auto-timer nil)
(loophole-use-auto-editing-timer nil)
(loophole-use-auto-start-editing-for-existing-binding nil)
(loophole-use-idle-prioritize nil)
(loophole-use-idle-save nil)
(loophole--define-map-font-lock-regexp
(concat "(\\(loophole-define-map\\)\\_>"
"[ ]*\\(\\(?:\\sw\\|\\s_\\|\\\\.\\)+\\)?"))
(loophole-font-lock 'multiline))
(let ((loophole-mode-lighter
(cdr (assq 'tag loophole-mode-lighter-preset-alist)))
(emulation-mode-map-alists '(loophole--map-alist))
(,temp-obarray (obarray-make))
(,mode-state loophole-mode)
(,local-variable-if-set-list
`((loophole--map-alist . nil)
(loophole--editing . t)
(loophole--timer-alist . nil)
(loophole--editing-timer . nil)
,@(seq-filter #'local-variable-if-set-p
(mapcar #'car loophole--map-alist))))
,local-variable-alist)
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(let (list)
(dolist (cons-or-variable ,local-variable-if-set-list)
(let ((variable (if (consp cons-or-variable)
(car cons-or-variable)
cons-or-variable)))
(if (local-variable-p variable)
(push `(,variable . ,(symbol-value variable)) list))))
(if list
(push `(,buffer . ,list) ,local-variable-alist)))))
(push `(nil . ,(mapcar (lambda (cons-or-variable)
(let ((variable (if (consp cons-or-variable)
(car cons-or-variable)
cons-or-variable)))
`(,variable . ,(default-value variable))))
,local-variable-if-set-list))
,local-variable-alist)
(with-temp-buffer
(let ((deflect-to-temp-obarray
(lambda (args)
(if (cadr args)
args
(let ((name (car args)))
(if (or (member
name
(mapcar
#'symbol-name
loophole--test-barriered-symbol-list))
(string-prefix-p "loophole" name))
(list name ,temp-obarray)
args))))))
(unwind-protect
(progn
(dolist (cons-or-variable ,local-variable-if-set-list)
(let ((variable (if (consp cons-or-variable)
(car cons-or-variable)
cons-or-variable)))
(remove-variable-watcher
variable #'loophole--follow-adding-local-variable)))
(dolist (buffer-binding-list (cdr ,local-variable-alist))
(with-current-buffer (car buffer-binding-list)
(remove-hook 'kill-buffer-hook
#'loophole--follow-killing-local-variable
t)
(remove-hook 'change-major-mode-hook
#'loophole--follow-killing-local-variable
t)
(dolist (binding (cdr buffer-binding-list))
(kill-local-variable (car binding)))))
(dolist (cons-or-variable ,local-variable-if-set-list)
(if (consp cons-or-variable)
(set-default (car cons-or-variable)
(cdr cons-or-variable))))
(advice-add 'intern :filter-args deflect-to-temp-obarray)
(advice-add 'unintern :filter-args deflect-to-temp-obarray)
,@body)
(advice-remove 'unintern deflect-to-temp-obarray)
(advice-remove 'intern deflect-to-temp-obarray)
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(dolist (cons-or-variable ,local-variable-if-set-list)
(let ((local-variable-if-set
(if (consp cons-or-variable)
(car cons-or-variable)
cons-or-variable)))
(if (local-variable-p local-variable-if-set)
(kill-local-variable local-variable-if-set))))))
(dolist (binding (cdar ,local-variable-alist))
(set-default (car binding) (cdr binding)))
(dolist (buffer-binding-list (cdr ,local-variable-alist))
(with-current-buffer (car buffer-binding-list)
(dolist (binding (cdr buffer-binding-list))
(set (car binding) (cdr binding)))
(when ,mode-state
(add-hook 'change-major-mode-hook
#'loophole--follow-killing-local-variable
nil t)
(add-hook 'kill-buffer-hook
#'loophole--follow-killing-local-variable
nil t))))
(if ,mode-state
(dolist (cons-or-variable ,local-variable-if-set-list)
(let ((variable (if (consp cons-or-variable)
(car cons-or-variable)
cons-or-variable)))
(add-variable-watcher
variable
#'loophole--follow-adding-local-variable)))))))))))
(defmacro loophole--test-with-keyboard-events (keyboard-events &rest body)
"Evaluate BODY followed by KEYBOARD-EVENTS.
KEYBOARD-EVENTS should be a string, vector representing
keyboard events, or a list of them .
In this macro, KEYBOARD-EVENTS are bound to
`overriding-terminal-local-map' transiently. Consequently,
KEYBOARD-EVENTS are ensured to be complete key sequence.
Bound entry is key-binding currently valid or undefined
if specified events are not bound to valid command.
However, if any form in BODY invokes minibuffer, transient
key bindings are disable. After the form exit minibuffer,
transient binding are re-enabled.
If keyboard-events is a list, its elements are bound to
`overriding-terminal-local-map' individually.
If KEYBOARD-EVENTS is something invalid and test is not
finished even after `loophole--test-wait-time' is spent,
`loophole-test-error' is signaled."
(declare (debug t) (indent 1))
(let ((exit-function (make-symbol "exit-function"))
(enter-transient-map (make-symbol "enter-transient-map"))
(exit-transient-map (make-symbol "exit-transient-map"))
(timer (make-symbol "timer")))
`(let ((unread-command-events (if (listp ,keyboard-events)
(apply #'append
(mapcar #'listify-key-sequence
,keyboard-events))
(listify-key-sequence ,keyboard-events)))
(,exit-function #'ignore))
(let ((,enter-transient-map
(lambda ()
(setq ,exit-function
(set-transient-map
(let ((map (make-sparse-keymap)))
(if (listp ,keyboard-events)
(dolist (key ,keyboard-events)
(define-key map key
(let ((entry (key-binding key)))
(if (commandp entry)
entry
#'undefined))))
(define-key map ,keyboard-events
(let ((entry (key-binding ,keyboard-events)))
(if (commandp entry)
entry
#'undefined))))
map)
t))))
(,exit-transient-map
(lambda ()
(funcall ,exit-function)
(setq ,exit-function #'ignore)))
(,timer nil))
(unwind-protect
(progn
(funcall ,enter-transient-map)
(add-hook 'minibuffer-setup-hook ,exit-transient-map)
(add-hook 'minibuffer-exit-hook ,enter-transient-map)
(setq ,timer
(run-with-timer
loophole--test-wait-time nil
(lambda ()
(signal
'loophole-test-error
(list "Test with keyboard events is timed out")))))
,@body)
(if (timerp ,timer) (cancel-timer ,timer))
(remove-hook 'minibuffer-exit-hook ,enter-transient-map)
(remove-hook 'minibuffer-setup-hook ,exit-transient-map))))))
(defun loophole--test-set-pseudo-map-alist ()
"Set pseudo `loophole--map-alist' value.
This function must be used in
`loophole--test-with-pseudo-environment'."
(setq loophole--map-alist nil)
(setq-default loophole--map-alist nil)
(dolist (name-tag '(("loophole-1-map" . "1")
("loophole-2-map" . "2")
("loophole-test-a-map" . "a")
("loophole-test-b-map" . "b")
("loophole" . "loop")))
(let* ((name (car name-tag))
(tag (cdr name-tag))
(map-variable (intern name))
(state-variable (intern (concat name "-state"))))
(set map-variable (make-sparse-keymap))
(set state-variable t)
(put map-variable :loophole-state-variable state-variable)
(put state-variable :loophole-map-variable map-variable)
(put map-variable :loophole-tag tag)
(setq loophole--map-alist
(cons `(,state-variable . ,(symbol-value map-variable))
loophole--map-alist))
(setq-default loophole--map-alist
(cons `(,state-variable . ,(symbol-value map-variable))
(default-value 'loophole--map-alist)))))
(make-variable-buffer-local (intern "loophole-2-map-state"))
(make-variable-buffer-local (intern "loophole-test-b-map-state"))
(make-variable-buffer-local (intern "loophole-state"))
(setq loophole--map-alist (reverse loophole--map-alist))
(setq-default loophole--map-alist (reverse
(default-value 'loophole--map-alist))))
;; Auxiliary functions
(ert-deftest loophole-test-map-variable ()
"Test for `loophole-map-variable'."
(loophole--test-with-pseudo-environment
(loophole--test-set-pseudo-map-alist)
(should (eq (loophole-map-variable (intern "loophole-1-map-state"))
(intern "loophole-1-map")))
(should (eq (loophole-map-variable (intern "loophole-test-a-map-state"))
(intern "loophole-test-a-map")))
(should (eq (loophole-map-variable (intern "loophole-state"))
(intern "loophole")))
(should-error (loophole-map-variable (intern "loophole-2-map"))
:type 'error :exclude-subtypes t)
(should-error (loophole-map-variable (intern "loophole-test-b-map"))
:type 'error :exclude-subtypes t)
(should-error (loophole-map-variable (intern "loophole"))
:type 'error :exclude-subtypes t)
(should-error (loophole-map-variable 0) :type 'wrong-type-argument)
(should-error (loophole-map-variable 1.0) :type 'wrong-type-argument)
(should-error (loophole-map-variable ?c) :type 'wrong-type-argument)
(should-error (loophole-map-variable (intern "s"))
:type 'error :exclude-subtypes t)
(should-error (loophole-map-variable (cons 0 0))
:type 'wrong-type-argument)
(should-error (loophole-map-variable (string ?s))
:type 'wrong-type-argument)
(should-error (loophole-map-variable (vector ?v))
:type 'wrong-type-argument)))
(ert-deftest loophole-test-state-variable ()
"Test for `loophole-state-variable'."
(loophole--test-with-pseudo-environment
(loophole--test-set-pseudo-map-alist)
(should (eq (loophole-state-variable (intern "loophole-1-map"))
(intern "loophole-1-map-state")))
(should (eq (loophole-state-variable (intern "loophole-test-a-map"))
(intern "loophole-test-a-map-state")))
(should (eq (loophole-state-variable (intern "loophole"))
(intern "loophole-state")))
(should-error (loophole-state-variable (intern "loophole-2-map-state"))
:type 'error :exclude-subtypes t)
(should-error (loophole-state-variable (intern "loophole-test-b-map-state"))
:type 'error :exclude-subtypes t)
(should-error (loophole-state-variable (intern "loophole-state"))
:type 'error :exclude-subtypes t)
(should-error (loophole-state-variable 0) :type 'wrong-type-argument)
(should-error (loophole-state-variable 1.0) :type 'wrong-type-argument)
(should-error (loophole-state-variable ?c) :type 'wrong-type-argument)
(should-error (loophole-state-variable (intern "s"))
:type 'error :exclude-subtypes t)
(should-error (loophole-state-variable (cons 0 0))
:type 'wrong-type-argument)
(should-error (loophole-state-variable (string ?s))
:type 'wrong-type-argument)
(should-error (loophole-state-variable (vector ?v))
:type 'wrong-type-argument)))
(ert-deftest loophole-test-map-variable-list ()
"Test for `loophole-map-variable-list'."
(let ((meet-requirement
(lambda ()
(let ((return (loophole-map-variable-list)))
(or (null return)
(and (consp return)
(seq-every-p #'loophole-registered-p return)
(equal (mapcar #'loophole-state-variable return)
(mapcar #'car loophole--map-alist))))))))
(loophole--test-with-pseudo-environment
(should (funcall meet-requirement))
(loophole--test-set-pseudo-map-alist)
(should (funcall meet-requirement)))))
(ert-deftest loophole-test-state-variable-list ()
"Test for `loophole-state-variable-list'."
(let ((meet-requirement
(lambda ()
(let ((return (loophole-state-variable-list)))
(or (null return)
(and (consp return)
(seq-every-p (lambda (state-variable)
(loophole-registered-p
(loophole-map-variable state-variable)
state-variable))
return)
(equal return
(mapcar #'car loophole--map-alist))))))))
(loophole--test-with-pseudo-environment
(should (funcall meet-requirement))
(loophole--test-set-pseudo-map-alist)
(should (funcall meet-requirement)))))
(ert-deftest loophole-test-key-equal ()
"Test for `loophole-key-equal'."
(loophole--test-with-pseudo-environment
(should (loophole-key-equal (string ?a) (vector ?a)))
(should-not (loophole-key-equal (string ?A) (vector ?\S-a)))
(should (loophole-key-equal (string ?\C-a) (vector ?\C-a)))
(should (loophole-key-equal (string ?\e ?a) (vector ?\e ?a)))
(should (loophole-key-equal (string ?\e ?a) (string (+ ?a (lsh 2 6)))))
(should (loophole-key-equal (string ?\e ?a) (vector ?\M-a)))
(should (loophole-key-equal (string ?\e ?/) (vector ?\e ?/)))
(should (loophole-key-equal (string ?\e ?/) (vector ?\M-/)))
(should (loophole-key-equal (kbd "DEL") (vector ?\^?)))
(should (loophole-key-equal (string ?\e ?\C-a) (vector ?\e ?\C-a)))
(should (loophole-key-equal (string ?\e ?\C-a) (vector ?\C-\M-a)))
(should-error (loophole-key-equal 0 0) :type 'wrong-type-argument)
(should-error (loophole-key-equal 1.0 1.0) :type 'wrong-type-argument)
(should-error (loophole-key-equal ?c ?c) :type 'wrong-type-argument)
(should-error (loophole-key-equal (intern "s") (intern "s"))
:type 'wrong-type-argument)
(should-error (loophole-key-equal (cons 0 0) (cons 0 0))
:type 'wrong-type-argument)))
(ert-deftest loophole-test-local-variable-if-set-list ()
"Test for `loophole-local-variable-if-set-list'."
(loophole--test-with-pseudo-environment
(should (equal (loophole-local-variable-if-set-list)
(list 'loophole--map-alist
'loophole--editing
'loophole--timer-alist
'loophole--editing-timer)))
(loophole--test-set-pseudo-map-alist)
(should (equal (loophole-local-variable-if-set-list)
(list 'loophole--map-alist
'loophole--editing
'loophole--timer-alist
'loophole--editing-timer
(intern "loophole-2-map-state")
(intern "loophole-test-b-map-state")
(intern "loophole-state"))))))
(ert-deftest loophole-test-read-key ()
"Test for `loophole-read-key'."
(loophole--test-with-pseudo-environment
(loophole--test-with-keyboard-events (vector ?a)
(should (loophole-key-equal (loophole-read-key "") (vector ?a))))
(loophole--test-with-keyboard-events (vector ?A)
(should (loophole-key-equal (loophole-read-key "") (vector ?A))))
(loophole--test-with-keyboard-events (vector ?\C-a)
(should (loophole-key-equal (loophole-read-key "") (vector ?\C-a))))
(loophole--test-with-keyboard-events (vector ?\M-a)
(should (loophole-key-equal (loophole-read-key "") (vector ?\M-a))))
(loophole--test-with-keyboard-events (vector ?\C-x ?\C-f)
(should (loophole-key-equal (loophole-read-key "") (vector ?\C-x ?\C-f))))
(loophole--test-with-keyboard-events (vector ?\C-\M-f)
(should (loophole-key-equal (loophole-read-key "") (vector ?\C-\M-f))))
(loophole--test-with-keyboard-events (vector ?\C-\S-f)
(should (loophole-key-equal (loophole-read-key "") (vector ?\C-\S-f))))
(loophole--test-with-keyboard-events (vector ?\M-\S-f)
(should (loophole-key-equal (loophole-read-key "") (vector ?\M-\S-f))))
(loophole--test-with-keyboard-events (vector ?\H-a)
(should (loophole-key-equal (loophole-read-key "") (vector ?\H-a))))
(loophole--test-with-keyboard-events (vector ?\s-a)
(should (loophole-key-equal (loophole-read-key "") (vector ?\s-a))))
(loophole--test-with-keyboard-events (vector ?\S-a)
(should (loophole-key-equal (loophole-read-key "") (vector ?\S-a))))
(loophole--test-with-keyboard-events (vector ?\A-a)
(should (loophole-key-equal (loophole-read-key "") (vector ?\A-a))))
(let* ((quit-binding-key (where-is-internal 'keyboard-quit nil t))
(quit-key (or quit-binding-key [?\C-g])))
(loophole--test-with-keyboard-events quit-key
(unless quit-binding-key
(define-key overriding-terminal-local-map quit-key #'keyboard-quit))
(should (condition-case nil
(progn (loophole-read-key "") nil)
(quit t))))
(loophole--test-with-keyboard-events quit-key
(unless quit-binding-key
(define-key overriding-terminal-local-map quit-key #'keyboard-quit))
(should (loophole-key-equal (let ((loophole-allow-keyboard-quit nil))
(loophole-read-key ""))
quit-key))))))
(provide 'loophole-tests)
;;; loophole-tests.el ends here
|
package com.example.mtg.utility.tasksGenerators;
import com.example.mtg.databinding.FragmentCountBinding;
import java.math.BigDecimal;
import java.util.Locale;
import java.util.Random;
public class AdvantageTasksGenerator {
private final FragmentCountBinding binding;
public AdvantageTasksGenerator(FragmentCountBinding binding) {
this.binding = binding;
}
public void generateIntegerDivTask() {
Random random = new Random();
int a;
int b;
do {
a = random.nextInt(20000) - 10000;
b = random.nextInt(198) + 2;
if (b != 100 && b != 101) {
b = b - 100;
}
} while (a % b != 0);
String task;
if (a >= 0 && b >= 0) {
task = a + " : " + b + " = ";
} else if (a >= 0) {
task = a + " : " + "(" + b + ")" + " = ";
} else if (b >= 0) {
task = "(" + a + ")" + " : " + b + " = ";
} else {
task = "(" + a + ")" + " : " + "(" + b + ")" + " = ";
}
binding.taskText.setText(task);
}
public void generateIntegerMultiTask() {
Random random = new Random();
int a = random.nextInt(200) - 100;
int b = random.nextInt(200) - 100;
String task;
if (a >= 0 && b >= 0) {
task = a + " x " + b + " = ";
} else if (a >= 0) {
task = a + " x " + "(" + b + ")" + " = ";
} else if (b >= 0) {
task = "(" + a + ")" + " x " + b + " = ";
} else {
task = "(" + a + ")" + " x " + "(" + b + ")" + " = ";
}
binding.taskText.setText(task);
}
public void generateIntegerSubTask() {
Random random = new Random();
int a = random.nextInt(20000) - 10000;
int b = random.nextInt(20000) - 10000;
String task;
if (a >= 0 && b >= 0) {
task = a + " - " + b + " = ";
} else if (a >= 0) {
task = a + " - " + "(" + b + ")" + " = ";
} else if (b >= 0) {
task = "(" + a + ")" + " - " + b + " = ";
} else {
task = "(" + a + ")" + " - " + "(" + b + ")" + " = ";
}
binding.taskText.setText(task);
}
public void generateIntegerAddTask() {
Random random = new Random();
int a = random.nextInt(20000) - 10000;
int b = random.nextInt(20000) - 10000;
String task;
if (a >= 0 && b >= 0) {
task = a + " + " + b + " = ";
} else if (a >= 0) {
task = a + " + " + "(" + b + ")" + " = ";
} else if (b >= 0) {
task = "(" + a + ")" + " + " + b + " = ";
} else {
task = "(" + a + ")" + " + " + "(" + b + ")" + " = ";
}
binding.taskText.setText(task);
}
public void generateNaturalDivTask() {
Random random = new Random();
int a;
int b;
do {
a = random.nextInt(10000)+1;
b = random.nextInt(98) + 2;
} while (a % b != 0);
String task = a + " : " + b + " = ";
binding.taskText.setText(task);
}
public void generateNaturalSubTask() {
Random random = new Random();
int a = random.nextInt(10000)+1;
int b = random.nextInt(10000)+1;
String task;
if (a > b) {
task = a + " - " + b + " = ";
} else {
task = b + " - " + a + " = ";
}
binding.taskText.setText(task);
}
public void generateNaturalMultiTask() {
Random random = new Random();
int a = random.nextInt(100)+2;
int b = random.nextInt(100)+2;
String task = a + " x " + b + " = ";
binding.taskText.setText(task);
}
public void generateNaturalAddTask() {
Random random = new Random();
int a = random.nextInt(10000)+1;
int b = random.nextInt(10000)+1;
String task = a + " + " + b + " = ";
binding.taskText.setText(task);
}
private void generateDecimalDivTask() {
double a;
double b;
double random1;
double random2;
double c;
String doubleForTask;
String[] doubles;
do {
random1 = new Random().nextDouble();
a = 1.0 + (random1 * (1000.0 - 0.0));
a = Double.parseDouble(String.format(Locale.US, "%.1f", a));
random2 = new Random().nextDouble();
b = 1.0 + (random2 * (100.0 - 0.0));
b = Double.parseDouble(String.format(Locale.US, "%.1f", b));
c = a / b;
doubleForTask = String.valueOf(c);
doubles = doubleForTask.split("\\.");
} while (doubles.length ==1 || doubles[1].length() != 1);
String task = BigDecimal.valueOf(a).stripTrailingZeros().toPlainString() + " : " + BigDecimal.valueOf(b).stripTrailingZeros().toPlainString() + " = ";
binding.taskText.setText(task);
}
private void generateDecimalSubTask() {
double random1 = new Random().nextDouble();
double a = 0.0 + (random1 * (1000.0 - 0.0));
a = Double.parseDouble(String.format(Locale.US, "%.3f", a));
double random2 = new Random().nextDouble();
double b = 0.0 + (random2 * (1000.0 - 0.0));
b = Double.parseDouble(String.format(Locale.US, "%.3f", b));
String task;
String s = BigDecimal.valueOf(a).stripTrailingZeros().toPlainString();
String s1 = BigDecimal.valueOf(b).stripTrailingZeros().toPlainString();
if (a > b) {
task = s + " - " + s1 + " = ";
} else {
task = s1 + " - " + s + " = ";
}
binding.taskText.setText(task);
}
private void generateDecimalMultiTask() {
double random1 = new Random().nextDouble();
double a = 0.0 + (random1 * (10.0 - 0.0));
a = Double.parseDouble(String.format(Locale.US, "%.1f", a));
double random2 = new Random().nextDouble();
double b = 0.0 + (random2 * (10.0 - 0.0));
b = Double.parseDouble(String.format(Locale.US, "%.1f", b));
String task = BigDecimal.valueOf(a).stripTrailingZeros().toPlainString() + " * " + BigDecimal.valueOf(b).stripTrailingZeros().toPlainString() + " = ";
binding.taskText.setText(task);
}
private void generateDecimalAddTask() {
double random1 = new Random().nextDouble();
double a = 0.0 + (random1 * (1000.0 - 0.0));
a = Double.parseDouble(String.format(Locale.US, "%.3f", a));
double random2 = new Random().nextDouble();
double b = 0.0 + (random2 * (1000.0 - 0.0));
b = Double.parseDouble(String.format(Locale.US, "%.3f", b));
String task = BigDecimal.valueOf(a).stripTrailingZeros().toPlainString() + " + " +BigDecimal.valueOf(b).stripTrailingZeros().toPlainString() + " = ";
binding.taskText.setText(task);
}
public void generateTask(int taskType, int typeNumber) {
switch (typeNumber) {
case 1:
switch (taskType) {
case 1:
generateNaturalAddTask();
break;
case 2:
generateNaturalMultiTask();
break;
case 3:
generateNaturalSubTask();
break;
case 4:
generateNaturalDivTask();
break;
}
break;
case 2:
switch (taskType) {
case 1:
generateIntegerAddTask();
break;
case 2:
generateIntegerMultiTask();
break;
case 3:
generateIntegerSubTask();
break;
case 4:
generateIntegerDivTask();
break;
}
break;
case 3:
switch (taskType) {
case 1:
generateDecimalAddTask();
break;
case 2:
generateDecimalMultiTask();
break;
case 3:
generateDecimalSubTask();
break;
case 4:
generateDecimalDivTask();
break;
}
break;
}
}
}
|
<template>
<div>
<el-form
ref="metadata_form_refs"
:model="metadata_form"
size="small"
label-width="80px"
>
<el-row>
<el-col :span="12">
<el-form-item label="名称" prop="name">
<el-input
v-model="metadata_form.name"
placeholder="请输入名称"
></el-input>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="命名空间" prop="namespace">
<el-input
v-model="metadata_form.namespace"
placeholder=""
></el-input>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-form-item label="注解" prop="annotations">
<el-button
size="small"
icon="el-icon-circle-plus"
@click="add_annotation"
></el-button>
<el-tooltip placement="right" effect="light">
<div
slot="content"
v-for="(item, index) in annotations_list"
:key="index"
>
<el-tag size="mini" type="info">{{ item.key }}</el-tag>
<el-tag size="mini" type="success">{{ item.value }}</el-tag>
<br />
</div>
<el-button
type="info"
icon="el-icon-collection-tag"
size="small"
></el-button>
</el-tooltip>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="标签" prop="labels">
<el-button
size="small"
icon="el-icon-circle-plus"
@click="add_label"
></el-button>
<el-tooltip placement="right" effect="light">
<div
slot="content"
v-for="(item, index) in labels_list"
:key="index"
>
<el-tag size="mini" type="info">{{ item.key }}</el-tag>
<el-tag size="mini" type="success">{{ item.value }}</el-tag>
<br />
</div>
<el-button
type="info"
icon="el-icon-collection-tag"
size="small"
></el-button>
</el-tooltip>
</el-form-item>
</el-col>
</el-row>
</el-form>
<LabelDialog
:title="annotation_title"
:visible="annotation_visible"
:key_value_list="annotation_key_value_list"
@delete_kv="annotation_delete_kv"
@cancel_delete_kv="annotation_cancel_delete_kv"
@dynamic_kv="annotation_dynamic_kv"
@cancel_submit_kv="annotation_cancel_submit_kv"
@submit_kv="annotation_submit_kv"
></LabelDialog>
<LabelDialog
:title="label_title"
:visible="label_visible"
:key_value_list="label_key_value_list"
@delete_kv="label_delete_kv"
@cancel_delete_kv="label_cancel_delete_kv"
@dynamic_kv="label_dynamic_kv"
@cancel_submit_kv="label_cancel_submit_kv"
@submit_kv="label_submit_kv"
></LabelDialog>
</div>
</template>
<script>
import LabelDialog from "./labelDialog";
export default {
components: {
LabelDialog,
},
props: {
metadata_form: {
type: Object,
default: function () {
return {};
},
},
},
watch: {
metadata_form: {
handler(newVal) {
let metadata_obj = Object.assign({}, newVal);
// console.log("===", metadata_obj);
this.labels_list = [];
for (const [key, value] of Object.entries(metadata_obj.labels)) {
this.labels_list.push({
key: key,
value: value,
});
}
this.annotations_list = [];
for (const [key, value] of Object.entries(metadata_obj.annotations)) {
this.annotations_list.push({
key: key,
value: value,
});
}
},
deep: true,
immediate: true,
},
},
data() {
return {
metadata_obj: {
name: "",
namespace: "",
annotations: {},
labels: {},
creationTimestamp: {
seconds: 0,
},
},
annotations_list: [],
annotation_title: "新增注解",
annotation_visible: false,
annotation_key_value_list: [{ isAdd: true, key: "", value: "" }],
labels_list: [],
label_title: "新增标签",
label_visible: false,
label_key_value_list: [{ isAdd: true, key: "", value: "" }],
};
},
methods: {
add_annotation() {
this.annotation_visible = true;
this.annotation_key_value_list = [{ isAdd: true, key: "", value: "" }];
},
annotation_delete_kv(row) {
this.annotation_key_value_list = this.annotation_key_value_list.filter(
(item) => item !== row
);
},
annotation_cancel_delete_kv() {
this.$message({
type: "warning",
message: "你考虑的很全面",
});
},
annotation_dynamic_kv(row) {
if (row.isAdd) {
this.annotation_key_value_list.slice(-1)[0].isAdd = false;
this.annotation_key_value_list.push({
isAdd: true,
key: "",
value: "",
});
} else {
this.annotation_key_value_list = this.annotation_key_value_list.filter(
(item) => item !== row
);
}
},
annotation_cancel_submit_kv() {
this.annotation_visible = false;
},
annotation_submit_kv() {
this.annotation_visible = false;
this.annotations_list = this.annotations_list.concat(
this.annotation_key_value_list
);
},
add_label() {
this.label_visible = true;
this.label_key_value_list = [{ isAdd: true, key: "", value: "" }];
},
label_delete_kv(row) {
this.label_key_value_list = this.label_key_value_list.filter(
(item) => item !== row
);
},
label_cancel_delete_kv() {
this.$message({
type: "warning",
message: "你考虑的很全面",
});
},
label_dynamic_kv(row) {
if (row.isAdd) {
this.label_key_value_list.slice(-1)[0].isAdd = false;
this.label_key_value_list.push({
isAdd: true,
key: "",
value: "",
});
} else {
this.label_key_value_list = this.label_key_value_list.filter(
(item) => item !== row
);
}
},
label_cancel_submit_kv() {
this.label_visible = false;
},
label_submit_kv() {
this.label_visible = false;
this.labels_list = this.labels_list.concat(this.label_key_value_list);
},
},
};
</script>
<style scoped>
.el-input {
width: 200px;
}
.el-select {
width: 200px;
}
.el-button {
vertical-align: top;
}
</style>
|
import { Button, Col, Form, Input, Row, Select, Upload, notification } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { faChevronLeft } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import './unit.scss';
import config from '../../../config';
import { useCreateUnit, useGetUnit, useUpdateUnit } from '../../../hooks/api';
import { useEffect, useState } from 'react';
import SpinLoading from '../../../layouts/Ecommerce/components/SpinLoading';
function UnitFormPage() {
let { id } = useParams();
const navigate = useNavigate();
const [form] = Form.useForm();
const { data, isLoading } = id ? useGetUnit(id) : { data: null, isLoading: null };
const [processing, setProcessing] = useState(false);
useEffect(() => {
if (isLoading || !data) return;
let unit = data.data;
form.setFieldsValue({
name: unit?.name,
status: unit?.status,
});
}, [isLoading, data]);
const mutationCreate = useCreateUnit({
success: () => {
notification.success({
message: 'Thêm thành công',
description: 'Đơn vị sản phẩm đã được thêm',
});
navigate(config.routes.admin.unit);
},
error: (err) => {
notification.error({
message: 'Thêm thất bại',
description: 'Có lỗi xảy ra khi thêm đơn vị sản phẩm',
});
},
mutate: () => {
setProcessing(true);
},
settled: () => {
setProcessing(false);
},
});
const mutationUpdate = useUpdateUnit({
success: () => {
notification.success({
message: 'Chỉnh sửa thành công',
description: 'Đơn vị sản phẩm đã được chỉnh sửa',
});
navigate(config.routes.admin.unit);
},
error: (err) => {
notification.error({
message: 'Chỉnh sửa thất bại',
description: 'Có lỗi xảy ra khi chỉnh sửa đơn vị sản phẩm',
});
},
mutate: () => {
setProcessing(true);
},
settled: () => {
setProcessing(false);
},
});
const onAdd = async () => {
try {
await form.validateFields();
} catch {
return;
}
await mutationCreate.mutateAsync({
name: form.getFieldValue('name'),
});
};
const onEdit = async () => {
try {
await form.validateFields();
} catch {
return;
}
await mutationUpdate.mutateAsync({
id: id,
body: {
name: form.getFieldValue('name'),
status: form.getFieldValue('status'),
},
});
};
if (isLoading && id)
return (
<div className="flex justify-center">
<SpinLoading />
</div>
);
return (
<div className="form-container">
<div className="flex items-center gap-[1rem]">
<FontAwesomeIcon
onClick={() => navigate(config.routes.admin.unit)}
className="text-[1.6rem] bg-[--primary-color] p-4 rounded-xl text-white cursor-pointer"
icon={faChevronLeft}
/>
<h1 className="font-bold">{id ? 'Cập nhật thông tin' : 'Thêm đơn vị sản phẩm'}</h1>
</div>
<div className="flex items-center justify-start rounded-xl shadow text-[1.6rem] text-black gap-[1rem] bg-white p-7">
<div className="flex flex-col gap-[1rem]">
<p>ID</p>
<code className="bg-blue-100 p-2">{data?.data?.id || '_'}</code>
</div>
<div className="flex flex-col gap-[1rem]">
<p>Ngày tạo</p>
<code className="bg-blue-100 p-2">
{data?.data?.createdAt
? new Date(data?.data?.createdAt).toLocaleString()
: '__/__/____'}
</code>
</div>
<div className="flex flex-col gap-[1rem]">
<p>Ngày cập nhật</p>
<code className="bg-blue-100 p-2">
{data?.data?.updatedAt
? new Date(data?.data?.updatedAt).toLocaleString()
: '__/__/____'}
</code>
</div>
</div>
<div className="bg-white p-7 mt-5 rounded-xl shadow">
<Form
name="unit-form"
layout="vertical"
form={form}
initialValues={{
remember: true,
}}
labelCol={{
span: 5,
}}
>
<Row gutter={16}>
<Col span={12}>
<Form.Item
label="Tên đơn vị"
name="name"
rules={[
{
required: true,
message: 'Nhập tên danh mục!',
},
]}
>
<Input />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="Trạng thái" name="status">
<Select
onChange={(v) => form.setFieldValue('status', v)}
defaultValue={true}
showSearch
>
<Option value={false}>Vô hiệu lực </Option>
<Option value={true}>Kích hoạt</Option>
</Select>
</Form.Item>
</Col>
</Row>
<div className="flex justify-between items-center gap-[1rem]">
<Button className="min-w-[10%]">Đặt lại</Button>
<Button
loading={processing}
onClick={id ? onEdit : onAdd}
className="bg-blue-500 text-white min-w-[10%]"
>
{id ? 'Cập nhật' : 'Thêm mới'}
</Button>
</div>
</Form>
</div>
</div>
);
}
export default UnitFormPage;
|
/*************************************************************************
* This file is part of MeeRadio for Nokia N9.
* Copyright (C) 2012 Stanislav Ionascu <[email protected]>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
***************************************************************************/
#ifndef PLAYLIST_H
#define PLAYLIST_H
#include <QObject>
#include <QUrl>
class PlaylistPrivate;
class QMediaPlaylist;
class Playlist : public QObject
{
Q_OBJECT
Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged)
Q_PROPERTY(QUrl mediaUrl READ mediaUrl NOTIFY mediaUrlChanged)
Q_PROPERTY(int mediaUrlCount READ mediaUrlCount NOTIFY mediaUrlCountChanged)
Q_PROPERTY(QString errorString READ errorString NOTIFY errorStringChanged)
Q_PROPERTY(int cacheId READ cacheId WRITE setCacheId NOTIFY cacheIdChanged)
public:
explicit Playlist(QObject *parent = 0);
virtual ~Playlist();
void setUrl(const QUrl &url);
QUrl url() const;
QUrl mediaUrl() const;
int mediaUrlCount() const;
QString errorString() const;
void setCacheId(int id);
int cacheId() const;
Q_INVOKABLE void removeCache(int cacheId);
Q_SIGNALS:
void urlChanged();
void error();
void loaded();
void mediaUrlChanged();
void mediaUrlCountChanged();
void errorStringChanged();
void cacheIdChanged();
public Q_SLOTS:
void next();
private:
Q_PRIVATE_SLOT(d_func(), void _q_loaded())
Q_PRIVATE_SLOT(d_func(), void _q_error(QString))
Q_DECLARE_PRIVATE(Playlist)
PlaylistPrivate *d_ptr;
};
#endif // PLAYLIST_H
|
;;; packages.el --- outline-magic layer packages file for Spacemacs.
;;
;; Copyright (c) 2012-2017 Sylvain Benner & Contributors
;;
;; Author: Jack Coughlin <[email protected]>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;;; Commentary:
;; See the Spacemacs documentation and FAQs for instructions on how to implement
;; a new layer:
;;
;; SPC h SPC layers RET
;;
;;
;; Briefly, each package to be installed or configured by this layer should be
;; added to `outline-magic-packages'. Then, for each package PACKAGE:
;;
;; - If PACKAGE is not referenced by any other Spacemacs layer, define a
;; function `outline-magic/init-PACKAGE' to load and initialize the package.
;; - Otherwise, PACKAGE is already referenced by another Spacemacs layer, so
;; define the functions `outline-magic/pre-init-PACKAGE' and/or
;; `outline-magic/post-init-PACKAGE' to customize the package as it is loaded.
;;; Code:
(defconst outline-magic-packages
'(outline-magic)
"The list of Lisp packages required by the outline-magic layer.
Each entry is either:
1. A symbol, which is interpreted as a package to be installed, or
2. A list of the form (PACKAGE KEYS...), where PACKAGE is the
name of the package to be installed or loaded, and KEYS are
any number of keyword-value-pairs.
The following keys are accepted:
- :excluded (t or nil): Prevent the package from being loaded
if value is non-nil
- :location: Specify a custom installation location.
The following values are legal:
- The symbol `elpa' (default) means PACKAGE will be
installed using the Emacs package manager.
- The symbol `local' directs Spacemacs to load the file at
`./local/PACKAGE/PACKAGE.el'
- A list beginning with the symbol `recipe' is a melpa
recipe. See: https://github.com/milkypostman/melpa#recipe-format")
(defun outline-magic/init-outline-magic ()
(use-package outline-magic
:init
(define-key outline-minor-mode-map (kbd "<tab>") 'outline-cycle)))
;;; packages.el ends here
|
{% extends 'core/base.html' %}
{% load dashboardextras %}
{% block title %}Проекты | {% endblock %}
{% block content %}
<div id="projects-app">
<nav class="breadcrumb" aria-label="breadcrumbs">
<ul>
<li><a href="{% url 'dashboard' %}">Информационная панель</a></li>
<li class="is-active"><a href="{% url 'project:get_projects' %}" aria-current="page">Проекты</a></li>
</ul>
</nav>
<div class="columns is-multiline">
<div class="column is-4">
<h1 class="title">Проекты</h1>
{% if team.plan.max_projects_per_team > team.projects.count %}
<a @click="showAddProjectModal = !showAddProjectModal" class="button is-success">Добавить проект</a>
{% else %}
<div class="notification is-warning">
Ваша группа достигла лимита по проектам.<br>
{% if team.created_by == request.user %}
<a href="{% url 'team:plans' %}">Обновить план</a>
{% else %}
Свяжитесь с владельцем группы
{% endif %}
</div>
{% endif %}
</div>
</div>
<div class="columns is-multiline">
{% for project in projects %}
<div class="column is-3">
<div class="notification">
<h2 class="is-size-5">{{ project.title }}</h2>
<p class="is-size-7">Зарегистрированнное время: {{ project.registered_time|format_minutes }}</p>
<p class="is-size-7">Задачи: {{ project.get_num_tasks_todo }}</p>
<hr>
<a href="{% url 'project:get_project' project.id %}" class="button is-success">Подробнее</a>
</div>
</div>
{% empty %}
<div class="column is-3">
<div class="notification">
У вас еще нет проектов...
</div>
</div>
{% endfor %}
</div>
<div class="modal" :class="{'is-active': showAddProjectModal}">
<div class="modal-background"></div>
<form method="post" action="." @submit="validateForm">
{% csrf_token %}
<div class="modal-card">
<div class="modal-card-head">
<p class="modal-card-title">Добавить проект</p>
</div>
<div class="modal-card-body">
<div class="field">
<label>Название проекта</label>
<div class="control">
<input type="text" name="title" id="id_title" v-model="title" class="input">
</div>
</div>
<div class="notification is-danger" v-if="showError">
Название проекта не указано!
</div>
</div>
<footer class="modal-card-foot">
<button class="button is-success">Создать</button>
<button class="button" @click="showAddProjectModal = !showAddProjectModal">Отменить</button>
</footer>
</div>
</form>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
const ProjectsApp = {
data() {
return {
showAddProjectModal: false,
title: '',
showError: false
}
},
delimiters: ['[[', ']]'],
methods: {
validateForm(e) {
if (this.title) {
return true
}
this.showError = true
e.preventDefault()
return false
}
}
}
Vue.createApp(ProjectsApp).mount('#projects-app')
</script>
{% endblock %}
|
import React from "react";
import { ComponentStory, ComponentMeta } from "@storybook/react";
import Header from "../components/Header/Header";
export default {
title: "Example/Header",
component: Header,
parameters: {
// More on Story layout: https://storybook.js.org/docs/react/configure/story-layout
layout: "fullscreen",
},
argTypes: {
fontSize: { control: "number" },
backgroundColor: { control: "color" },
borderRadius: { control: "number" },
borderColor: { control: "color" },
color: {control: "color"},
marginTop: {control: "number"}
},
} as ComponentMeta<typeof Header>;
const Template: ComponentStory<typeof Header> = (args) => <Header {...args}/>;
export const LoggedIn = Template.bind({});
LoggedIn.args = {};
|
<?php
namespace App\Http\Controllers;
use JWTAuth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Illuminate\Http\Response;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Hash;
class ApiController extends Controller
{
public $token = true;
public function register(Request $request)
{
//Validate data
$validator = Validator::make($request->all(), [
'name' => 'required|min:5|max:30',
'email' => 'required|email',
'password' => 'required|min:5'
]);
//Send failed response if request is not valid
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], Response::HTTP_UNAUTHORIZED);
}
//Request is valid, create new user
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
if ($this->token) {
return $this->login($request);
}
//User created, return success response
return response()->json([
'success' => true,
'message' => 'User created successfully',
'data' => $user
], Response::HTTP_OK);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
$jwt_token = null;
//valid credential
$validator = Validator::make($credentials,[
'email' => 'required|email',
'password' => 'required|min:5'
]);
//Send failed response if request is not valid
if ($validator->fails()) {
return response()->json(['error' => $validator->messages()], Response::HTTP_OK);
}
//Request is validated
//Crean token
try {
if (!$jwt_token = JWTAuth::attempt($credentials)) {
return response()->json([
'success' => false,
'message' => 'Login credentials are invalid.',
], Response::HTTP_UNAUTHORIZED);
}
} catch (JWTException $e) {
return response()->json([
'success' => false,
'message' => 'Could not create token.',
'credentials' => $credentials
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
//Token created, return with success response and jwt token
return response()->json([
'success' => true,
'token' => $jwt_token,
]);
}
public function logout(Request $request)
{
//valid credential
$validator = Validator::make($request->only('token'), [
'token' => 'required'
]);
//Send failed response if request is not valid
if ($validator->fails()) {
return response()->json(['error' => $validator->messages()], 200);
}
//Request is validated, do logout
try {
JWTAuth::invalidate($request->token);
return response()->json([
'success' => true,
'message' => 'User has been logged out'
], Response::HTTP_OK);
} catch (JWTException $exception) {
return response()->json([
'success' => false,
'message' => 'Sorry, user cannot be logged out'
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
public function get_user(Request $request)
{
$this->validate($request, [
'token' => 'required'
]);
$user = JWTAuth::authenticate($request->token);
return response()->json(['user' => $user]);
}
}
|
//
// ContentView.swift
// Patch
//
// Created by Nate Leake on 4/1/23.
//
import SwiftUI
struct RootView: View {
@Environment (\.managedObjectContext) var managedObjContext
@EnvironmentObject var colors: ColorContent
@EnvironmentObject var dataController: DataController
@EnvironmentObject var monthViewing: CurrentlyViewedMonth
@EnvironmentObject var startingBalancesStore: StartingBalanceStore
@EnvironmentObject var templatesStore: TemplatesStore
@FetchRequest(sortDescriptors: [SortDescriptor(\.name)]) var accountData: FetchedResults<Account>
@State var selectedTabs: Tabs = .home
@State var showingMonthBalance: Bool = false
func loadBalances() async {
let m = Task{
do {
try await startingBalancesStore.load()
checkPresentBalanceSheet()
return true
} catch {
fatalError(error.localizedDescription)
}
}
print(await m.value)
}
func loadCategoryTempaltes() async {
let t = Task {
do {
try await templatesStore.load()
checkAutoApplyCategoryTemplate()
return true
} catch {
fatalError(error.localizedDescription)
}
}
print(await t.value)
}
func checkPresentBalanceSheet(){
if startingBalancesStore.balances.isEmpty {
showingMonthBalance = true
}
else if startingBalancesStore.balances[startingBalancesStore.balances.endIndex-1].month < monthViewing.monthStart{
showingMonthBalance = true
}
}
func checkAutoApplyCategoryTemplate(){
if monthViewing.currentCategories == [] {
for cat in templatesStore.templates[0].categories{
dataController.addCategory(account: accountData[0], date: monthViewing.monthStart, name: cat.name, limit: cat.limit, type: cat.type, symbolName: cat.symbol)
}
}
}
var body: some View {
ZStack(alignment: .top) {
colors.Fill
.ignoresSafeArea()
VStack(spacing:0){
switch selectedTabs {
case .home:
HomeView()
case .categories:
CategoryView(dataController: self.dataController, monthViewing: self.monthViewing)
case .accounts:
AccountsView()
case .settings:
SettingsView()
.environmentObject(startingBalancesStore)
.environmentObject(templatesStore)
}
CustomTabBar(selectedTab: $selectedTabs)
}
.sheet(isPresented: $showingMonthBalance){
StartingBalanceSheetView()
{
Task {
do {
try await startingBalancesStore.save(balances: startingBalancesStore.balances)
}
catch {
fatalError(error.localizedDescription)
}
}
}
.environmentObject(startingBalancesStore)
}
// GeometryReader { reader in
// LinearGradient(
// gradient: Gradient(
// stops:[
// .init(color: colors.Fill.opacity(1.0), location: 0.9),
// .init(color: Color.clear, location: 1.0)
// ]
// ),
// startPoint: .top, endPoint: .bottom
// )
// .frame(height: reader.safeAreaInsets.top, alignment: .top)
// .ignoresSafeArea()
// }
} .onAppear{
Task {
await loadBalances()
await loadCategoryTempaltes()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var dataController = DataController(isPreviewing: true)
static var previews: some View {
RootView()
.environmentObject(dataController)
.environmentObject(ColorContent())
.environment(\.managedObjectContext, dataController.context)
.environmentObject(CurrentlyViewedMonth(MOC: dataController.context))
.environmentObject(StartingBalanceStore())
}
}
|
import './App.css';
import React,{useState} from 'react';
const Square=({value,onSquareClick})=>{
return (
<button className="square-button" onClick={onSquareClick} >{value}</button>
);
}
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
function Board({xIsSet,onPlay,squares}) {
let winner="";
const handleClick=(index)=>{
let arr=squares.slice();
if(arr[index]||calculateWinner(squares)){
return ;
}
if(xIsSet)
arr[index]='X';
else
arr[index]='O';
onPlay(arr);
}
let foundWinner=calculateWinner(squares);
if(foundWinner){
winner=("Winner is: "+foundWinner);
}
else{
winner=("Current player: "+(xIsSet?'X':'O'));
}
return (
<>
<div>{winner}</div>
<div className="board-row">
<Square value={squares[0]} onSquareClick={() => handleClick(0)} />
<Square value={squares[1]} onSquareClick={() => handleClick(1)} />
<Square value={squares[2]} onSquareClick={() => handleClick(2)} />
</div>
<div className="board-row">
<Square value={squares[3]} onSquareClick={() => handleClick(3)} />
<Square value={squares[4]} onSquareClick={() => handleClick(4)} />
<Square value={squares[5]} onSquareClick={() => handleClick(5)} />
</div>
<div className="board-row">
<Square value={squares[6]} onSquareClick={() => handleClick(6)} />
<Square value={squares[7]} onSquareClick={() => handleClick(7)} />
<Square value={squares[8]} onSquareClick={() => handleClick(8)} />
</div>
</>
);
}
export default function Game(){
const [history,setHistory]=useState([Array(9).fill(null)]);
const [currentMove,setCurrentMove]=useState(0);
const xIsSet=(currentMove%2===0);
const currState=history[currentMove];
function handleOnPlay(newArr){
const nextHistory = [...history.slice(0,currentMove + 1), newArr];
setHistory(nextHistory);
setCurrentMove(nextHistory.length-1);
}
const jumpTo=(move)=>{
setCurrentMove(move);
}
const moves=history.map((squares,move)=>{
let description;
if(move>0)description="Move number "+move;
else description="Empty game";
return (
<div key={move} >
<button onClick={()=>jumpTo(move)} >{description}</button>
</div>
);
});
return <>
<div className="board">
<Board xIsSet={xIsSet} onPlay={handleOnPlay} squares={currState}/>
</div>
<div className="display-table">{moves}</div>
</>
}
|
package dev.mayra.courses.entities.user;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class UserLoginDTO {
@NotBlank(message = "The username can't be blank")
@Schema(description = "Fill the username", required = true, example = "namelastname")
private String username;
@NotBlank(message = "The password can't be blank")
@Schema(description = "Fill the password", required = true, example = "mypassword")
private String password;
}
|
# Copyright (C) 2016, 2017, 2018, 2023 Carolina Feher da Silva
# 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 3 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, see <https://www.gnu.org/licenses/>.
"""Analyse if the ratings (effort, understanding, and complexity) differ by condition"""
from os.path import join
import pandas as pd
from cmdstanpy import CmdStanModel
import numpy as np
parts_rts = pd.read_csv(join("..", "..", "data", "ratings.csv"))
model = CmdStanModel(stan_file="ratings_model.stan")
for rating in ("effort", "understanding", "complexity"):
print(rating.capitalize(), "analysis...")
model_dat = {
"K": 5,
"N": len(parts_rts),
"ratings": list(parts_rts[rating] + 1),
"condition": list((parts_rts.condition == "story").astype("int")),
}
fit = model.sample(
chains=4,
data=model_dat,
iter_warmup=2000,
iter_sampling=10000,
show_progress=True,
)
print(fit.summary(percentiles=(2, 5, 50, 95, 97)))
eta = fit.stan_variable("eta")
print(f"Effect of story instructions on {rating}:")
print(
"95% CI:", round(np.quantile(eta, 0.025), 3), round(np.quantile(eta, 0.975), 3)
)
print(
"Posterior probabilities (< 0 and > 0):",
round(np.mean(eta < 0), 3),
round(np.mean(eta > 0), 3),
)
print(
"Bayes factors (< 0 and > 0):",
round(np.mean(eta < 0) / np.mean(eta >= 0), 1),
round(np.mean(eta > 0) / np.mean(eta <= 0), 1),
)
print()
|
import { withSentry } from "@sentry/nextjs";
import { NextApiHandler } from "next";
import { createOrderFromBodyOrId } from "@/saleor-app-checkout/backend/payments/createOrderFromBody";
import {
KnownPaymentError,
MissingUrlError,
UnknownPaymentError,
} from "@/saleor-app-checkout/backend/payments/errors";
import { createAdyenCheckoutPaymentLinks } from "@/saleor-app-checkout/backend/payments/providers/adyen";
import { reuseExistingAdyenSession } from "@/saleor-app-checkout/backend/payments/providers/adyen/verifySession";
import { createDummyPayment } from "@/saleor-app-checkout/backend/payments/providers/dummy/createPayment";
import { createMolliePayment } from "@/saleor-app-checkout/backend/payments/providers/mollie";
import { reuseExistingMollieSession } from "@/saleor-app-checkout/backend/payments/providers/mollie/verifySession";
import { createStripePayment } from "@/saleor-app-checkout/backend/payments/providers/stripe/createPayment";
import { reuseExistingStripeSession } from "@/saleor-app-checkout/backend/payments/providers/stripe/verifySession";
import {
CreatePaymentResult,
ReuseExistingSessionParams,
ReuseExistingSessionResult,
} from "@/saleor-app-checkout/backend/payments/types";
import { updatePaymentMetafield } from "@/saleor-app-checkout/backend/payments/updatePaymentMetafield";
import { allowCors, getBaseUrl } from "@/saleor-app-checkout/backend/utils";
import { OrderFragment } from "@/saleor-app-checkout/graphql";
import { PayRequestErrorResponse, PayRequestResponse } from "@/saleor-app-checkout/types/api/pay";
import { OrderPaymentMetafield } from "@/saleor-app-checkout/types/common";
import { safeJsonParse } from "@/saleor-app-checkout/utils";
import { unpackPromise } from "@/saleor-app-checkout/utils/promises";
import {
assertUnreachable,
PaymentMethods,
PaymentProviders,
PayRequestBody,
} from "checkout-common";
const reuseExistingSession = ({
orderId,
provider,
method,
privateMetafield,
}: ReuseExistingSessionParams): ReuseExistingSessionResult => {
const payment: OrderPaymentMetafield = JSON.parse(privateMetafield);
if (payment.provider !== provider || payment.method !== method || !payment.session) {
return;
}
const params = {
payment,
orderId,
provider,
method,
privateMetafield,
};
switch (payment.provider) {
case "mollie":
return reuseExistingMollieSession(params);
case "adyen":
return reuseExistingAdyenSession(params);
case "stripe":
return reuseExistingStripeSession(params);
case "dummy":
return undefined;
default:
assertUnreachable(payment.provider);
}
};
const getPaymentResponse = async (
body: PayRequestBody,
appUrl: string
): Promise<PayRequestResponse> => {
if (!PaymentProviders.includes(body.provider)) {
throw new KnownPaymentError(body.provider, ["UNKNOWN_PROVIDER"]);
}
if (!PaymentMethods.includes(body.method)) {
throw new KnownPaymentError(body.provider, ["UNKNOWN_METHOD"]);
}
const order = await createOrderFromBodyOrId(body);
if (order.privateMetafield) {
const existingSessionResponse = await reuseExistingSession({
orderId: order.id,
privateMetafield: order.privateMetafield,
provider: body.provider,
method: body.method,
});
if (existingSessionResponse) {
return existingSessionResponse;
}
}
const [paymentUrlError, data] = await unpackPromise(
getPaymentUrlIdForProvider(body, order, appUrl)
);
if (paymentUrlError) {
console.error(paymentUrlError);
throw new UnknownPaymentError(body.provider, paymentUrlError, order);
}
const { id, url } = data;
if (!url) {
throw new MissingUrlError(body.provider, order);
}
const response: PayRequestResponse = {
ok: true,
provider: body.provider,
orderId: order.id,
data: {
paymentUrl: url,
},
};
const payment: OrderPaymentMetafield = {
provider: body.provider,
method: body.method,
session: id,
};
await updatePaymentMetafield(order.id, payment);
return response;
};
const handler: NextApiHandler = async (req, res) => {
if (req.method !== "POST") {
res.status(405).send({ message: "Only POST requests allowed" });
return;
}
const [error, body] =
typeof req.body === "string"
? safeJsonParse<PayRequestBody>(req.body)
: [null, req.body as PayRequestBody];
if (error) {
console.error(error, req.body);
res.status(400).send({ message: "Invalid JSON" });
return;
}
try {
const appUrl = getBaseUrl(req);
const response = await getPaymentResponse(body, appUrl);
return res.status(200).json(response);
} catch (err) {
if (err instanceof KnownPaymentError) {
return res.status(400).json({
ok: false,
provider: err.provider,
errors: err.errors,
} as PayRequestErrorResponse);
}
if (err instanceof UnknownPaymentError) {
return res.status(500).json({
ok: false,
provider: err.provider,
orderId: err.order?.id,
});
}
if (err instanceof MissingUrlError) {
return res.status(503).json({ ok: false, provider: err.provider, orderId: err.order?.id });
}
console.error(err);
return res.status(500).json({ ok: false, provider: body.provider });
}
};
const getPaymentUrlIdForProvider = (
body: PayRequestBody,
order: OrderFragment,
appUrl: string
): Promise<CreatePaymentResult> => {
const createPaymentData = {
order,
redirectUrl: body.redirectUrl,
method: body.method,
appUrl,
};
switch (body.provider) {
case "mollie":
return createMolliePayment(createPaymentData);
case "adyen":
return createAdyenCheckoutPaymentLinks(createPaymentData);
case "stripe":
return createStripePayment(createPaymentData);
case "dummy":
return createDummyPayment({
redirectUrl: `${body.redirectUrl}?order=${order.id}&dummyPayment=true`,
});
default:
assertUnreachable(body.provider);
}
};
export default withSentry(allowCors(handler));
|
<!DOCTYPE html>
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>FakeHouse-backer</title>
<meta name="description" content="FakeHouse-backer">
<meta name="keywords" content="FakeHouse-backer">
<meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
<!-- 引入样式 -->
<link rel="stylesheet" href="../plugins/elementui/index.css">
<link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/style.css">
</head>
<body class="hold-transition">
<div id="app">
<div class="content-header">
<h1>权限管理<small>权限管理</small></h1>
<el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>权限管理</el-breadcrumb-item>
<el-breadcrumb-item>权限管理</el-breadcrumb-item>
</el-breadcrumb>
</div>
<div class="app-container">
<div class="box">
<div class="filter-container">
<el-input placeholder="权限名称" v-model="pagination.queryString" style="width: 200px;" class="filter-item"></el-input>
<el-button @click="findQueryPage()" class="dalfBut">查询</el-button>
<el-button type="primary" class="butT" @click="handleCreate()">新建权限</el-button>
</div>
<!-- 列表数据展示 -->
<el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
<el-table-column type="index" align="center" label="序号"></el-table-column>
<el-table-column prop="name" label="权限名" align="center"></el-table-column>
<el-table-column prop="keyword" label="权限关键词" align="center"></el-table-column>
<el-table-column prop="description" label="权限描述" align="center"></el-table-column>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页插件 -->
<div class="pagination-container">
<el-pagination
class="pagiantion"
@current-change="handleCurrentChange"
:current-page="pagination.currentPage"
:page-size="pagination.pageSize"
layout="total, prev, pager, next, jumper"
:total="pagination.total">
</el-pagination>
</div>
<!-- 新增标签弹层 -->
<div class="add-form">
<el-dialog title="新增权限" :visible.sync="dialogFormVisible">
<el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="权限名" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="权限关键词" prop="keyword">
<el-input v-model="formData.keyword"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="权限描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="handleAdd()">确定</el-button>
</div>
</el-dialog>
</div>
<!-- 编辑标签弹层 -->
<div class="add-form">
<el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit">
<el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="权限名" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="权限关键词" prop="keyword">
<el-input v-model="formData.keyword"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="权限描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible4Edit = false">取消</el-button>
<el-button type="primary" @click="handleEdit()">确定</el-button>
</div>
</el-dialog>
</div>
</div>
</div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
var vue = new Vue({
el: '#app',
data:{
pagination: {//分页相关模型数据
currentPage: 1,//当前页码
pageSize:10,//每页显示的记录数
total:0,//总记录数
queryString:null//查询条件
},
dataList: [],//当前页要展示的分页列表数据
formData: {},//表单数据
dialogFormVisible: false,//增加表单是否可见
dialogFormVisible4Edit:false,//编辑表单是否可见
rules: {//校验规则
name: [{ required: true, message: '权限名称为必填项', trigger: 'blur' }],
keyword: [{ required: true, message: '权限关键字为必填项', trigger: 'blur' }]
}
},
//钩子函数,VUE对象初始化完成后自动执行
created() {
this.findPage();//VUE对象初始化完成后调用分页查询方法,完成分页查询
},
methods: {
//权限不足提示
showMessage(r){
if(r == 'Error: Request failed with status code 403'){
//权限不足
this.$message.error('无访问权限');
return;
}else{
this.$message.error('未知错误');
return;
}
},
//编辑
handleEdit() {
//进行表单校验 使用项目的data下的rule进行校验
this.$refs['dataEditForm'].validate((valid) => {
if(valid){
//表单校验通过,可以提交数据
axios.put("/FakeHouse-backer/permission/edit.do",this.formData).then((res) => {
if(res.data.flag){
//弹出成功提示信息
this.$message({
type:'success',
message:res.data.message
});
}else{
//执行失败
this.$message.error(res.data.message);
}
}).catch((res)=>
{
// 修改失败,权限不足
this.showMessage(res);
}).finally(() => {
//不管成功还是失败,都调用分页查询方法
this.findPage();
//隐藏编辑窗口
this.dialogFormVisible4Edit = false;
// 重置表单数据
this.resetForm();
});
}else{
//表单校验不通过
this.$message.error("表单数据校验失败!");
return false;
}
});
},
//添加
handleAdd () {
//进行表单校验
this.$refs['dataAddForm'].validate((valid) => {
if(valid){
//表单校验通过,发生ajax请求,将录入的数据提交到后台进行处理
axios.post("/FakeHouse-backer/permission/add.do",this.formData).then((res) => {
if(res.data.flag){//执行成功
//关闭新增窗口
this.dialogFormVisible = false;
//新增成功后,重新调用分页查询方法,查询出最新的数据
this.findPage();
//弹出提示信息
this.$message({
message:res.data.message,
type:'success'
});
}else{//执行失败
//弹出提示
this.$message.error(res.data.message);
}
});
}else{
//校验不通过
this.$message.error("数据校验失败,请检查你的输入信息是否正确!");
return false;
}
});
},
//分页查询
findPage() {
//发送ajax请求,提交分页相关请求参数(页码、每页显示记录数、查询条件)
var param = {
currentPage:this.pagination.currentPage,
pageSize:this.pagination.pageSize,
queryString: this.pagination.queryString
};
axios.post("/FakeHouse-backer/permission/findPage.do",param).then((res)=>{
if(res.data.flag) {
//解析Controller响应回的数据,为模型数据赋值
this.pagination.total = res.data.data.total;
this.dataList = res.data.data.rows;
}else
{
// 查询数据失败
this.$message.error(res.data.message);
}
}).catch((bad)=> {
// 403处理
this.showMessage(bad);
});
},
// 与findPage的区别是 该方法会将页数设置为1
findQueryPage()
{
//发送ajax请求,提交分页相关请求参数(页码、每页显示记录数、查询条件)
var param = {
currentPage:1,
pageSize:this.pagination.pageSize,
queryString: this.pagination.queryString
};
axios.post("/FakeHouse-backer/permission/findPage.do",param).then((res)=>{
if (res.data.flag)
{
//解析Controller响应回的数据,为模型数据赋值
this.pagination.total = res.data.data.total;
this.dataList = res.data.data.rows;
this.pagination.currentPage = 1;
}else
{
// 查询数据失败
this.$message.error(res.data.message)
}
}).catch((bad)=> {
// 403错误处理
this.showMessage(bad);
});
},
// 重置表单
resetForm() {
this.formData = {};//重置数据
},
// 弹出添加窗口
handleCreate() {
// 清空上次的数据
this.resetForm();
//弹出新增窗口
this.dialogFormVisible = true;
},
// 弹出编辑窗口
handleUpdate(row) {
//回显数据,发送ajax请求根据ID查询当前检查项数据
axios.get("/FakeHouse-backer/permission/findById.do?id=" + row.id).then((res) => {
if (res.data.flag) {
//进行回显,基于VUE的数据绑定实现
// res.data获取到返回的json对象的数据
this.formData = res.data.data;
//弹出编辑窗口
this.dialogFormVisible4Edit = true;
} else {
//查询失败,弹出提示
this.$message.error(res.data.message);
}
}).catch((res) => {
// 请求失败 发生异常
this.showMessage(res);
});
},
//切换页码
handleCurrentChange(currentPage) {
//设置最新的页码
this.pagination.currentPage = currentPage;
//重新调用findPage方法进行分页查询
this.findPage();
},
// 删除
handleDelete(row) {//row其实是一个json对象
//alert(row.id);
// row.id的内容其实是没有显示出来的,但是它是存在的,在查询数据库的时候,就设置到了该对象中,只是没有将数据展示出来而已
// 弹出确认框
this.$confirm("你确定要删除当前数据吗?","提示",{//确认框
type:'warning'
}).then(()=>{
//用户点击确定按钮,发送ajax请求,将检查项ID提交到Controller进行处理
axios.delete("/FakeHouse-backer/permission/delete.do?id=" + row.id).then((res) => {
if(res.data.flag){
//执行成功
//弹出成功提示信息
this.$message({
type:'success',
message:res.data.message
});
//重新进行分页查询
this.findQueryPage();
}else{
//执行失败
this.$message.error(res.data.message);
}
}).catch((bres)=>
{
// 请求不成功,可能由于服务器异常或者客户端异常
// 处理403响应, 调用工具方法进行处理
this.showMessage(bres);
});
}).catch(()=>{
this.$message({
type:'info',
message:'操作已取消'
});
});
}
}
})
</script>
</html>
|
<template>
<div class="prop-types">
<p>{{typeof bool}}: {{bool}}</p>
<p>{{typeof num}}: {{num}}</p>
<p>{{typeof str}}: {{str}}</p>
<p>{{typeof arr}}: {{arr}}</p>
<p>{{typeof obj}}: {{obj}}</p>
<p>{{typeof fn}}: {{fn}}</p>
<button @click="() => $emit('event', {
random: Math.random().toString(36).substr(2, 7)
})">Emit Event</button>
</div>
</template>
<script>
export default {
name: 'prop-types',
props: {
bool: {
type: Boolean
},
num: {
type: Number,
default: 235
},
str: {
type: String,
default: 'CNC',
note: `Any of the following strings: <br> <code>['CNC', 'IM', '3DP', 'SM']</code> <br><br> 'SM' is only available in the AMER region.`
},
arr: {
type: Array,
required: true,
},
obj: {
type: Object,
default: () => ({foo: 'bar'}),
note: `Any 'ol object.`
},
fn: {
type: Function,
default: () => (function() {
return 'default fn'
}),
note: 'Any function',
}
},
events: {
event: {
type: Object,
note: 'Emits an event containing a random string <br/> Example: <code>{random: "1j38hf2"}</code>',
}
},
}
</script>
<style lang="stylus" scoped>
.prop-types {
border: 1px solid #aaa
}
</style>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.